Binding to the same property of the same object will update all bindings on property change

Answered Binding to the same property of the same object will update all bindings on property change

  • Friday, August 10, 2012 8:02 PM
     
     

    I came across this one while trying to answer another thread. So, you have two or more text boxes in your XAML, with bindings to the same property of the same object:

    <TextBox Text="{Binding Name}" />
    <TextBox Text="{Binding Name}" />

    and a Model class:

    class MyClass
    {
     public string Name { get; set; }
    }

    and a DataContext:

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MyClass();
    }

    When the text changes in one TextBox and I move focus to the other, I would think the text in the second TextBox wouldn't change, because Name is neither a DependencyProperty nor MyClass implements INotifyPropertyChanged. But it works, making me thinking that WPF internally keeps track of bindings to the same property of the same object. Now, I implement Name property in MainWindow class and do

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    it still works, but not quite - at first it din't work at all. After restarting Windows (I thought because I have had too many Visual Studios opened for days) it worked, but only if there are no white spaces. So, the first scenario works fine no matter what you type. The second scenario wouldn't work if you type white spaces, Binding trace shows "...  is not a valid value for property 'Name'" in the Output Window. Tested in VS10 and VS12RC. Can anyone explain this behavior?


    PT

All Replies

  • Sunday, August 12, 2012 8:48 AM
     
     Answered

    1.- 'MyClass.Name' case:

    - binding updates will indeed work w/o INotifyPropertyChanged

    - limitations are:

      - degraded performance

      - view model code updating the property value 'MyClass.Name' will not update the corresponding UI TextBox

    http://10rem.net/blog/2010/12/17/puff-the-magic-poco-binding-and-inotifypropertychanged-in-wpf gives an excellent overview of this topic.

    --

    2.- 'MainWindow.Name' case: your local 'Name' property conflicts with the 'Name' property of the MainWindow FrameworkElement. Hence the problem of not accepting blanks.

    • Marked As Answer by ptsimb Sunday, August 12, 2012 12:15 PM
    •