« Degrees of Thread Safety | Main | Author Introduction: Bradley Grainger »
April 1, 2008
Handling the PropertyChanged event
When handling the PropertyChanged event of an object that implements INotifyPropertyChanged, one is tempted to write a handler like this:
void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Text")
UpdateText();
else if (e.PropertyName == "Icon")
UpdateIcon();
}
Strictly speaking, this isn't entirely correct. According to the documentation for the PropertyChanged event, “the PropertyChanged event can indicate all properties on the object have changed by using either null or string.Empty as the property name in the PropertyChangedEventArgs.” So, you're forced to write something like this:
void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
bool bAllChanged = string.IsNullOrEmpty(e.PropertyName);
if (bAllChanged || e.PropertyName == "Text")
UpdateText();
if (bAllChanged || e.PropertyName == "Icon")
UpdateIcon();
}
To make checking for this situation a little bit easier, and to increase the likelihood that we remember to do it, we put together a nice little extension method on PropertyChangedEventArgs called HasChanged:
public static bool HasChanged(this PropertyChangedEventArgs e,
string strPropertyName)
{
string strEventPropertyName = e.PropertyName;
return string.IsNullOrEmpty(strEventPropertyName) ||
strPropertyName == strEventPropertyName;
}
Now, proper handling of the PropertyChanged event is as easy as this:
void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.HasChanged("Text"))
UpdateText();
if (e.HasChanged("Icon"))
UpdateIcon();
}
Just remember not to use "else"...
Posted by Ed Ball at April 1, 2008 4:27 PM
Trackback Pings
TrackBack URL for this entry:
http://blog.logos.com/mt-cgi/mt-tb.cgi/201
Comments
Hello,
Is it real or just a joke for April 1.based on MSDN, it not seems that PropertyChangedEventArgs have a HasChanged method.
It's very funny rofl...
Michel4CE
Posted by: Michel4CE at April 22, 2008 6:45 AM
Hi Michel4CE,
The HasChanged method is entirely our own invention; the new "extension method" syntax of C# 3.0 allows it to appear as if it is a real method on PropertyChangedEventArgs, even though it's actually defined in one of our static utility classes.
Bradley
Posted by: Bradley Grainger at April 24, 2008 6:03 PM