Search code examples
wpfentity-frameworkmvvm

MVVM - Bind directly to Model object exposed from VM or implement a separate property in VM to access the Model properties


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?


Solution

  • 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.