Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DependencyProperty on ViewModel with Entity Framework

I am writing a desktop application in C# using the MVVM pattern with an Entity Framework model. I tend to use DependencyProperties in my VM's and have come to (generally) prefer this system over implementing INotifyPropertyChanged. I would like to keep things consistent. My VM accesses the Entities in the Model and I have managed to keep things pretty separate - the View has no knowlege of the VM except for binding and command names and the Model has know knowlege of the VM.

Using INotifyPropertyChanged in the VM, it seems pretty easy to update the Entities in the Model:

public string Forename
    {
        get { return CurrentPerson.Forename; }
        set
        {
            if (Forename != value)
            {
                CurrentPerson.Forename = value;
                NotifyPropertyChanged("Forename");
            }
        }
    }

...where CurrentPerson is a Person object auto-created by the Entity Data Model. There is therefore no private field created specifically to store the Forename.

With DependencyProperties, it appears that I would have to create a DP, add the default Property, using GetValue and Setvalue and then use the PropertyChangedCallback in order to update the CurrentPerson Entity. Calling a callback in this situation appears to be adding overhead for the sake of being consistent with my other VM's.

The question is therefore whether one or other of these methods is the way I should do things? In this instance, should I use a DependencyProperty or INotifyPropertyChanged? One thing that should be pointed out is that this will potentially be a very large scale project (with plugins and a lot of database accesses from different machines) and that everything really should be as reusable, and the modules as "disconnected", as possible.

like image 356
AJ. Avatar asked Nov 04 '22 16:11

AJ.


1 Answers

I would recommend using INotifyPropertyChanged instead of DependencyProperty. The main reason I stay away from DependencyProperty in ViewModels is because the DependencyProperty is located in WindowsBase.dll. This ties you to the Windows UI a bit too much (at least IMHO).

Using the INotifyPropertyChanged is a lot easier to maintain since it allows the various plugins to implement it the way they want. If you force Dependency Properties, all viewmodels need to inherit from DependencyObject.

See this article for more details about the use of INotifyPropertyChanged and DependencyProperty: http://kentb.blogspot.com/2009/03/view-models-pocos-versus.html

Another supporting answer: https://stackoverflow.com/a/783154/27669

like image 83
kevindaub Avatar answered Nov 15 '22 04:11

kevindaub