MVVM - Bind directly to the Model object accessible by the VM, or create a distinct property in the VM to access the Model properties.

entity-framework mvvm wpf

Question

Sorry if the title is confusing but I don't really know how to shorten my question. Anyway, here it goes.

I'm using WPF, Entity Framework and MVVM.

Currently, in my ViewModel, I have a property

public Model.Document Document {get;set;} //Model.Document is an EF Entity

Then, in XAML, I bind to

<TextBox Text={Binding Path=Document.Title}/>

Title is of course a Property on the Model.

Now following question came to my mind: To separate the Model from the View, wouldn't it be better if I added a property to the ViewModel like so

    public string Title
    {
        get { return Document.Title; }
        set { Document.Title = value; }
    }

and then bind like this:

<TextBox Text={Binding Path=Title}/>

Which way is recommended?

1
22
4/27/2011 3:00:10 PM

Accepted Answer

If you take a look at How Data Binding References are Resolved, you can see that there can be performance issues to consider when deciding how to expose the property you are going to bind to.

Does the Model.Document implement the INotifyPropertyChanged interface? If not, I would recommend adding a Title property to your view model and implement INotifyPropertyChanged on your view model such that when the Title is changed the PropertyChanged event is raised to notify the view.

Another approach would be to expose the Title on your view model as a DependencyProperty as the binding and render time is faster.

11
4/27/2011 3:24:31 PM

Popular Answer

You might have a look at the BookLibrary sample application of the WPF Application Framework (WAF). It uses the first approach and still follows the MVVM pattern (separation of concerns, unit testable).

This simplifies the ViewModels because the Binding uses the INotifyPropertyChanged implementation of the Entities. Otherwise, you have to synchronize changes manually between the ViewModels.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow