You have to fire the event. In the example on MSDN, they made a protected method OnPropertyChanged
to handle this easier (and to avoid duplicate code).
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
What this method does, is look whether there is an event handler assigned or not (if it is not assigned and you just call it, you'll get a NullReferenceException
). If there is one assigned, call this event handler. The event handler provided, has to have the signature of the PropertyChangedEventHandler
delegate. This signature is:
void MyMethod(object sender, PropertyChangedEventArgs e)
Where the first parameter has to be of the type object and represents the object that fires the event, and the second parameter contains the arguments of this event. In this case, your own class fires the event and thus give this
as parameter sender
. The second parameter contains the name of the property that has changed.
Now to be able to react upon the firing of the event, you have to assign an event handler to the class. In this case, you'll have to assign this in your addChatter
method. Apart from that, you'll have to first define your handler. In your NosyClass
you'll have to add a method to do this, for example:
private void chatter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("A property has changed: " + e.PropertyName);
}
As you can see, this method corresponds to the signature I explained before. In the second parameter, you'll be able to find the information of which parameter has been changed. Last thing to do, is add the event handler. Now in your addChatter
method, you'll have to assign this:
public void AddChatter(ChattyClass chatter)
{
myChatters.Add(chatter);
// Assign the event handler
chatter.PropertyChanged += new PropertyChangedEventHandler(chatter_PropertyChanged);
}
I would suggest you to read something about events in .NET / C#: http://msdn.microsoft.com/en-us/library/awbftdfh . I think after reading/learning this, things will be more clear to you.
You can find a console application here on pastebin if you would like to test it quickly (just copy/paste into a new console application).
With newer versions of C#, you can inline the call to the event handler:
// inside your setter
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyProperty)));
You could also use something like Fody PropertyChanged to automatically generated the necessary code (visit the link to their GitHub page, with samples).