Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 564
Gilles Radrizzi Avatar asked Apr 27 '11 15:04

Gilles Radrizzi


People also ask

What is binding in MVVM?

Data Binding allows you to effortlessly communicate across views and data sources. This pattern is important for many Android designs, including model view ViewModel (MVVM), which is currently one of the most common Android architecture patterns.

Should model or ViewModel implement INotifyPropertyChanged?

You should always have the Model implement INotifyPropertyChanged and this is just a mistake which would be corrected if this were developed from a code example to an application.

What is MVVM in WPF How does it work?

MVVM (Model-View-ViewModel) MVVM is a way of creating client applications that leverages core features of the WPF platform, allows for simple unit testing of application functionality, and helps developers and designers work together with less technical difficulties.


1 Answers

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.

like image 180
Oppositional Avatar answered Oct 26 '22 08:10

Oppositional