为什么绑定格式事件被调用两次?

时间:2010-07-13 17:31:29

标签: c# data-binding events format

我正在玩数据绑定,并注意到在下面的代码中加载表单时调用绑定格式两次。我认为只有当测试类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

1 个答案:

答案 0 :(得分:1)

简单的答案:“因为这是微软实施它的方式”。

目标是只对事件作出反应......无论什么时候发生......但是经常会发生。我们不能做任何假设。在某些情况下,您可能会在同一事件中被召唤六次。

我们只需要随身携带并继续保持精彩。