Lesson 03.6 – Update Player data with the PropertyChanged event

In this lesson, we will finish connecting the Model (Player.cs) to the View (MainWindow.xaml). With this change, when a property value changes on the Model or ViewModel, the View will automatically update.

 

 

Summary

  • An “Interface” defines the properties and functions that must exist in any class that “implements” the interface.
    • It also lets other classes know how the classes with the interface will work, and how they can be used.
  • Databinding does not automatically know when a property value changes in the DataContext object.
    • The View can know about changes to properties, if the ViewModel (or Model) classes implement the INotifyPropertyChanged interface.
    • When a class implements INotifyPropertyChanged, its properties “raise” a PropertyChanged “event”. The View “listens” for that event, and updates the UI, when it receives notification of the change.
  • To make the property raise the PropertyChanged event, when it gets a new value, they cannot be auto-properties.
    • We need to add extra code to the property “set”, to raise the Property Changed event, when the property is set to a new value.
    • To add this extra code, we need to add a “backing variable” for the property – a variable the property uses to store its value.
    • Then, we need to add a code to raise the PropertyChanged event, for anything that may be subscribed to the eventhandler, such as the View.

 

Source Code

 

Player.cs

 

MainWindow.xaml

 

MainWindow.xaml.cs

 

Return to main page

 

4 thoughts on “Lesson 03.6 – Update Player data with the PropertyChanged event

    1. Yes. Although, the property changed event is a built-in one that is automatically recognized. So, for the property changed event, we do not need to create the delegate, or manually connect from the “subscriber” (the ViewModel) to the “publisher” (the View).

      In future lessons, we will create our own custom events, for events like OnPlayerKilled and OnMonsterKilled. Those will require the delegate, subscribing, etc.

Leave a Reply

Your email address will not be published. Required fields are marked *