2010-07-13 99 views
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 

回答

1

簡單的回答:「因爲這是Microsoft實施它的方式」。

我們的目標是對事件做出反應......無論何時發生...但無論如何經常發生。我們不能做出任何假設。有些情況下,您可能會在同一事件中被召喚六次。

我們只需要滾動它,並繼續是真棒。

相關問題