Why is it that if I bind two controls, say 2 TextBoxes, to a single property of a model which does not implement INotifyPropertyChanged the content of two text boxes stay in sync? How is the other TextBox being notified of the other one updating the source?
Model:
namespace BindingExample
{
public class PersonModel
{
public string Name { get; set; }
}
}
View:
<Window x:Class="BindingExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingExample"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:PersonModel x:Key="person"></local:PersonModel>
<Style TargetType="TextBox">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Width" Value="100"/>
</Style>
</Window.Resources>
<Grid DataContext="{StaticResource person}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Row="1" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
The two textboxes in your example are using the same datacontext and actually share the same instance of the .NET object PersonModel, since the default setting of the static resource in the resource dictionary WPF is shared, i.e. when referencing to the static resource you will always get the same instance. More about the the x:Shared attribute on MSDN:
MSDN article about x:Shared attribute
An alternative to this is to set x:Shared to false to get a new instance everytime. In addition, I had to remove the binding to the datacontext in your example to individually be able to edit the values in the textboxes indivually.
The following XAML shows this:
The reason for x:Shared is set to true for resources in a resource dictionary is for efficiency reasons. By setting x:Shared on a resource (e.g. an object) in a resource dictionary in XAML will give us new instances everytime the resource is references and accessed. I had to remove the data context from the grid and set the source of the binding for the textboxes to the static resource person.