1
我正在玩弄數據綁定,並注意到在下面的代碼中加載表單時會調用綁定格式兩次。我以爲只有當測試類TextBoxText屬性綁定到textbox1時纔會發生。這是正常的嗎?如果不是,那麼我能做些什麼來防止它呢?請注意,當我按下按鈕1並且它更改測試類的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