I have successfully bound a control to a property on my page. The property I am binding to returns a class. The binding works but if I set the property to be a new instance of the class the UI is not updated.
Could anyone point be in the right direction to solve this issue, I have tried implementing INotifyPropertyChanged but this doesn’t work.
The Code is as follows..
XAML – Very Basic just trying to bind a label to a property at the minute.
<Grid>
<Label Content="{Binding StudentName}"></Label>
<Button Width="100" Height="75" Click="Button_Click" ></Button>
</Grid>
C#
this.DataContext = parentWindow.SelectedStudent;
The parent Window C# note parent window implements INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public UCStudent SelectedStudent
{
get
{
if (_selectedStudent == null)
{
_selectedStudent = new UCStudent();
}
return _selectedStudent;
}
set
{
if (_selectedStudent != value)
{
_selectedStudent = value;
OnPropertyChanged("SelectedStudent");
}
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
The issue is when I set the SelectedStudent property to be a new selected student the binding does not update.
While my approach uses generics and an expression, so I can strongly type my property changes, the concept is the same. Where I use an expression, you use a string. You’ll want to return if PropertyChanged is null. Otherwise, fire the event without declaring a new event handler first.
This approach allows the view model to strongly type the notification.