Question

As far as I know, there are 2 common ways to create a DataContext class, one is to implement INotifyPropertyChanged and the other one is to derive from DependencyObject.

Lots of people say the first way of implementing INotifyPropertyChanged is simpler and I agree.

But I don't agree totally because I think even implementing INotifyPropertyChanged is not simple enough but very tedious, because I must rewrite every setter function for the properties and fire the event, it's mostly copy & paste & modify things, which I dislike a lot. It's not elegant.

So I'm curious, are there any other ways to create a DataContext, for example, just derive from some class and all is done?

I know if the datacontext is a collection, there is a very easy way to do it, just inherit from ObservableCollection<>, which I think is a very good solution. But how about other classes?

Some 3rd party framework?

Was it helpful?

Solution

I have successfully used PostSharp to quickly implement the INotifyPropertyChanged very easily for all my ViewModels. In fact, this is really the canonical example for using Aspects, as demonstrated on the (current) front page;

[NotifyPropertyChanged]  
public class Person  
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public string FullName  
    {  
        get { return this.FirstName + " " + this.LastName; } 
    } 
} 

You'll find plenty of information on that site to show you how to do this.

Another (free) alternative might be to make use of a WPF/MVVM framework like Caliburn Micro, which includes 'base' types like PropertyChangedBase from which you can inherit your ViewModels, and minimise your code duplication.

OTHER TIPS

You can use an AOP framework like Postsharp which allows you to simply put an attribute onto your class and that generates all the the INotifyPropertyChanged glue code for you.

I wouldn't generally recommend this, but I'll mention it in case you're not aware: You don't actually need to implement dependency properties or INotifyPropertyChanged to make data binding work. When binding to a non-dependency-property owned by a class that does not implement INotifyPropertyChanged, WPF will automatically listen via PropertyDescriptor.AddValueChanged.

The reason it's not recommended is that PropertyDescriptor is global, so the reference between it and the listening target is permanent, causing a memory leak. See this page: http://support.microsoft.com/kb/938416

However, if you just want to get a demo / test app up and running quickly, this works perfectly fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top