Saturday, May 17, 2008

Enhanced INotifyPropertyChanged

Today, I found something very intresting regarding using of Linq Expressions. As you may know, binding objects in WPF required you to implement INotifyPropertyChanged interface (at least if you're using two-way binding). A typical implementation of this interface for Customer class would be :

But, as Jafar Husain points on his blog you can benefit from Linq Expressions and C# 3.0 extension methods to handle this nicely without hard-coding property names in strings!

Here's how it would look like with this technique :

The magic is in "GetPropertySymbol" extension method, which extracts the member name from the Lambda expression.
Submit this story to DotNetKicks Shout it

1 comment:

John Rusk said...

You can take this one step further with a library I wrote, called ActiveSharp. It lets you write your property setters something like this:

set { SetValue(_ref lastname, value); }

You don't even have to put the property name in as an expression, and yet you still get property change notifications.