Pages

Wednesday 26 November 2008

INotifyPropertyChanged

I had a conversation with Martin about INotifyPropertyChanged and it made me realise there was an (other) aspect of Binding that I hadn't appreciated.

So I created a little project to test my assumptions.

1) Business Class implements INotifyPropertyChanged

public class Person : INotifyPropertyChanged
{
private string _surname = "";
public string Surname
{
get { return _surname; }
set
{
_surname = value;
OnPropertyChanged("Surname");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
2) Model exposing two instances of Person. Model does not implement INPC

public class Model
{
public Person APerson { get; set; }
public Person AnotherPerson { get; set; }
public Model()
{
APerson = new Person();
AnotherPerson = new Person();
}
}
3) Bind to only one of the two instances of Person in the Model

<TextBlock Text="{Binding Model.APerson.Surname}"></TextBlock>
<Button Click="Button_Click">Go</Button>
4) Wire it all up

public partial class Window2 : Window
{
private Model _model = new Model();
public Model Model
{
get { return _model; }
set { _model = value; }
}
public Window2()
{
InitializeComponent();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Model.APerson.Surname = "Smith";
Model.AnotherPerson.Surname = "Jones";
}
}
Result:
PropertyChanged is only hooked up for APerson and not for AnotherPerson because nothing is bound to AnotherPerson in the xaml.

Conclusion:
I might need to revisit the changes I made to AbstractModel hooking up PropertyChanged and DataError. Currently they are hooked up when the Model is instantiated, regardless of whether there is any binding in the xaml.

No comments: