为什么绑定格式事件被调用两次?
我正在尝试数据绑定,并注意到在加载下面的代码中的表单时,绑定格式被调用了两次。我认为只有当测试类 TextBoxText 属性首次绑定到 textbox1 时才会发生一次。这是正常的吗?如果不是,那么我可以做什么来预防呢?请注意,当我按下 button1 并且它更改了测试类的 TextBoxText 属性时, format 事件将按预期触发一次。
public partial class Form1 : Form
{
Test _test = new Test();
public Form1()
{
InitializeComponent();
Binding binding = new Binding("Text", _test, "TextBoxText");
binding.Format += new ConvertEventHandler(Binding_Format);
this.textBox1.DataBindings.Add(binding);
}
private void Binding_Format(object sender, ConvertEventArgs e)
{
Debug.WriteLine("Format");
}
private void button1_Click(object sender, EventArgs e)
{
_test.TextBoxText = "test1";
}
}
class Test : INotifyPropertyChanged
{
private string _text;
public string TextBoxText
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged(new PropertyChangedEventArgs("TextBoxText"));
}
}
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged(this, e);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
I am playing around with data binding and noticed that the Binding Format is called twice upon loading the form in the code below. I thought it would only happen once when the test class TextBoxText property is fist bound to textbox1. Is this normal? If not, then what can I do to prevent it? Note, when I press button1 and it changes the TextBoxText property of the test class, the format event fires once as expected.
public partial class Form1 : Form
{
Test _test = new Test();
public Form1()
{
InitializeComponent();
Binding binding = new Binding("Text", _test, "TextBoxText");
binding.Format += new ConvertEventHandler(Binding_Format);
this.textBox1.DataBindings.Add(binding);
}
private void Binding_Format(object sender, ConvertEventArgs e)
{
Debug.WriteLine("Format");
}
private void button1_Click(object sender, EventArgs e)
{
_test.TextBoxText = "test1";
}
}
class Test : INotifyPropertyChanged
{
private string _text;
public string TextBoxText
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged(new PropertyChangedEventArgs("TextBoxText"));
}
}
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged(this, e);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的答案是:“因为这就是微软实现它的方式”。
我们的目标是对事件做出响应……无论何时发生……无论发生的频率如何。我们无法做出任何假设。在某些情况下,您可能会在同一事件中接到六次电话。
我们只需要顺其自然并继续保持出色。
The simple answer: "Because that is the way Microsoft implemented it".
The goal is to just respond to the event... whenever it happens... however often it occurs. We can't make any assumptions. There are cases where you might get called six times on the same event.
We just have to roll with it and continue to be awesome.