views:

29

answers:

1

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
A: 

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.

Brian Genisio