Best Practice for Binding ItemsControl in MVVM - c#

What is the best practice for binding a list of items to an ItemsControl when using the MVVM pattern?
1. Bind a list of ViewModels
Load the items from the database, create the models and all viewmodels and then bind a list of viewmodels to the ItemsControl.ItemsSource:
public class MyMainViewModel
{
public List<PersonViewModel> Persons { get; set; }
}
2. Bind a list of Models
Load the items from the database, create the models and then bind a list of those models directly to the ItemsControl.ItemsSource:
public class MyMainViewModel
{
public List<Person> Persons { get; set; }
}

I think the answer here is really it depends.
Firstly, you need to assess whether your view needs to interact with your model in such a way that it would make sense for a view model to be wrapped around a particular model. Let's look at an example:
public class WebsiteModel
{
public string URL { get; set; }
}
Here I have a very simple model which represents a website, nothing too fancy. I can create a view model which will encompass all websites, like a one to many relationship:
public class WebsitesViewModel
{
//A list of websites.
public List<WebsiteModel> Websites { get; set; }
//The command I will use to navigate, where the object parameter will be the WebsiteModel.
public ICommand NavigateCommand { get; set; }
...
public void Navigate(WebsiteModel model)
{
...
}
Here I want my view to be able to navigate to the URL using the browser. My view model holds a list of models and my command takes care of navigation.
The next method I can create a view model to represent a single model, I would say this is a SOLID approach:
public class WebsiteViewModel
{
//The website model
public WebsiteModel Website { get; set; }
//The command I will use to navigate, no parameters needed.
public ICommand NavigateCommand { get; set; }
...
public void Navigate()
{
...
}
In this scenario, I'll need another view model which will expose a list of WebsiteViewModel to my view.
public List<WebsiteViewModel> Websites { get; set; }
The truth is there isn't really a best practice. Neither method really trumps the other. There are benefits to each method, however the method to choose really depends on the implementation. In this scenario, method 2, I would say is overcomplicated. However it's not uncommon for a view model to become very large very quickly, and the need to separate concerns will force you to create smaller classes, and even view models to wrap your models inside, making method 2 a viable option.
So to wrap up. Neither method is best practice.

The only "correct" way to do it, is to use ViewModels all the way.
While initially more work, it gives you more flexibility and less bugs later on.
Don't for get, when you a model should only be valid in it's bounded context and when you bind your ViewModel to the view, you have a leaky abstraction. The View becomes aware of model and each change to the model, will affect your View.
Further more, refactoring doesn't work within XAML. So if you name a model property via refactoring, your XAML will still bind to the old property. This doesn't give you a compile error and your bounded element will just remain empty (in best case) or crash (in worst case).
This can be quite hard to figure out and fix. Also as Scroog1 commented, it introduces memory leaks. May not be noticeable in small applications, but ones working with big data sets it can lead to out of memory exceptions.
You should utilize an automapping library to map from Model to ViewModel in cases that allows it, this will reduce some boilerplate code. But remember to avoid ViewModel to Model automappings, as it's discouraged.
You want to avoid that a change in your model influences code in a different bounded context, i.e. you don't want to expose every database or model change in a rest service, even if the change do not influence the given rest action.
The same strategy can be applied to the n-layer model (View, ViewModel, (Domain) Model layer, Services and Infrastructure)

I think there is no correct way, using models is the pragmatic and simpler way, using view models is more time consuming but more decoupled...
You should have a look at this article:
http://blog.alner.net/archive/2010/02/09/mvvm-to-wrap-or-not-to-wrap.aspx
also: http://www.codeproject.com/Articles/61147/MVVM-Creating-ViewModel-Wrap-your-business-object

Related

How to access data when a viewModel depends on several models

I'm a novice trying to wrap my head around MVVM. I'm trying to build something and have not found an answer on how to deal with this:
I have several models/entities, some of which have logical connections and I am wondering where/when to bring it all together nicely.
Assume we have a PersonModel:
public class PersonModel
{
public int Id { get; set; }
public string Name { get; set; }
...
}
And a ClubModel:
public class ClubModel
{
public int Id { get; set; }
public string Name { get; set; }
...
}
And we have MembershipModel (a Person can have several Club memberships):
public class MembershipModel
{
public int Id { get; set; }
public PersonId { get; set; }
public ClubId { get; set; }
}
All these models are stored somewhere, and the models are persisted "as in" in that data storage.
Assume we have separate repositories in place for each of these models that supplies the standard CRUD operations.
Now I want to create a view model to manage all Persons, e.g. renaming, adding memberships, etc. -> PersonMangementViewModel.
In order to nicely bind a Person with all its properties and memberships, I would also create a PersonView(?)Model that can be used in the PersonManagementViewModel. It could contain e.g. view relevant properties and also the memberships:
public class PersonViewModel : PersonModel
{
public Color BkgnColor { get return SomeLogic(); }
public IEnumerable<MembershipModel> { get; set; }
...
}
My question here is, how would I smartly go about getting the Membership info into the PersionViewModel? I could of course create an instance of the MemberShipRepo directly in the PersionViewModel but that seems not nice, especially if you have a lot of Persons. I could also create all repositories in the PersonManagementViewModel and then pass references into the PersonViewModel.
Or does it make more sense to create another layer (e.g. "service" layer) that returns primarily the PersonViewModel, therefore uses the individual repositories and is called from the PersonManagementViewModel (thus removing the burden from it and allowing for re-use of the service elsewhere)?
Happy to have pointed out conceptional mistakes or some further reading.
Thanks
You are creating separate model for each table I guess. Does not matter, but your models are fragmented. You can consider putting related data together using Aggregate Root and Repository per Aggregate root instead of per model. This concept is discussed under DDD. But as you said you are new to MVVM, there is already lot much to learn. Involving DDD at this stage will only complicate the things.
If you decide to keep the things as is, best and quick thing I can guess is what you are doing now. Get instance of model from data store in View Model (or whatever your location) and map somehow. Tools like Automapper are good but they does not fit each situation. Do not hesitate to map by hand if needed. You can also use mix approach (Automapper + map by hand) to simplify the things.
About service layer, sure... why not. Totally depends on you. If used, this layer typically contain your business logic, mapping, formatting of data, validations etc. Again, each of that thing is up to you.
My suggestions:
Focus on your business objectives first.
Design patterns are good and helpful. Those are extract of many exceptionally capable developers to solve specific problem. Do use them. But, do not unnecessarily stick to it. Read above suggestion. In short, avoid over-engineering. Design patterns are created to solve specific problem. If you do not have that problem, then do not mess-up your code with unnecessary pattern.
Read about Aggregate Root, DDD, Repository etc.
Try your best to avoid Generic Repository.

MVVM Xamarin Forms Design

So I was looking at https://github.com/xamarin/Sport as an example I came across when googling something for my current project. It is similar to what Im working on because I use an azure backend as well.
I have a question about their mvvm layout. I thought that in mvvm the models were sort of POCOs and not supposed to implement INotifyPropertyChanged. Arent they acting as both a Model and a ViewModel in this case? Look at the Athlete model and the AthleteViewModel. The VM has a property for for Athlete and so the model is used as a VM as well.
In my project, if I had the same types, I would have an Athlete model, an AthleteViewModel and an AthletePageViewModel. Where the Athlete and AthleteVM would be automapped. The only reason to populate and or create the Athlete is to persist it to the service or local storage.
Is one way more "correct" than the other way? Or am I just doing it wrong and over complicating it? I almost don't want to continue with the way I'm doing it because I dont want to have a bunch of "extra" model files if I can just use some of my VMs as models.
Thanks.
There's no ultimate master set of strict rules that you need to follow in order to implement the MVVM design pattern. In fact, the guidelines are generally quite blurry.
From what I've seen, there are a couple of different methods of which a model may be exposed to the view. Here they are:
Method 1 - INotifyPropertyChanged in the Model
public class Car : INotifyPropertyChanged
{
private string _Model;
public string Model
{
get { return _Model; }
set
{
_Model = value;
NotifyOfPropertyChange();
}
}
...
}
public class CarViewModel
{
//The entire model is exposed to the view.
public Car Model { get; set; }
...
Method 2 - INotifyPropertyChanged in the View Model
public class CarViewModel
{
private Car _Car;
//The model property is exposed to the view, not the model itself.
public string CarModel
{
get { return _Car.Model; }
set
{
_Car.Model = value;
NotifyOfPropertyChange();
}
}
...
In terms of a preferred method, I would say method 2 is the better option. Why?
The Model object is not exposed to the view.
The View Model only exposes what the View needs.
Method 2 does have its downsides. Imagine if you needed to expose lots of model properties, or imagine if your model changes, it is certainly easier to simply implement INotifyPropertyChanged in the model and expose it to the view. Programmers are lazy by nature, therefore in order to save hassle, you'll see method 1 just as much as method 2.
But that isn't a bad thing.
Is one way more "correct" than the other way? Or am I just doing it wrong and over complicating it?
Remember, the MVVM design pattern is just a pattern. Neither options are correct, it's mostly down to the developers preference how they choose to approach the implementation of the pattern, as long as the main MVVM concepts are there, that's all that matters.

Two concurrent views with one ViewModel

I'm getting mixed answers reading through other posts, but say I have one main ViewModel, which handles two related data models
public partial class Product
{
public string ProductName { get; set; }
public int TemplateID { get; set; }
public virtual Template Template { get; set; }
}
public Template()
{
this.Products = new ObservableCollection<Product>();
}
public int TemplateID { get; set; }
public string TemplateName { get; set; }
public virtual ObservableCollection<Product> Products { get; set; }
}
Currently, have two separate Views and ViewModels, one that shows all data "byTemplates" and another that shows all the data "byProducts". Both allow CRUD operations. In order to get rid of duplicate codes and commands, I want to merge these two views into one.
Would I still require two ViewModels? Can I have both working off the same data instance? (so if I went and inserted something under the "ByTemplates" view, and switch to "ByProducts" before saving to the database, I'd still see all the changes I have?
EDIT:
I'm currently using tabs to faciliate this.
My views are here:
By Product Tab
By Templates Tab (user can select a Template, and the "Associated Products" ListView will show all prodcucts linked to "template")
What you are saying is pretty much possible, viewmodel can contain multiple models combined together acting as one parent viewmodel and it is up to view which all properties that it is interested in binding with.
Having two separate views or not is a design discussion but it is not mandatory. Neither having one viewmodel per model is required. Purpose of having view model is to get rid of direct dependency on a particular business model and merge and mold data according to UI needs. So yes you can do what you intend to do.
Please share detail xaml and existing model/viewmodel if you want in depth how to do, else you are all set.
I would tend to use a single viewmodel where both views are interconnected. An example being detail and summary view of the same data perhaps.
In the scenario you describe, if both views are leveraging the same data and methods then sure, keep them as one viewmodel. If however you are parametising each command to work on a subset then it sounds as though seperation will be better - I would look to do this by base classing the common elements to improve reuse and maintenance and then extend into specific viewmodels for each subset. That also offers better extensions later.

Having ViewModel call Actions instead of executing Commands and publishing events?

In this hypothetical question, let's say the ViewModel publishes a rather complex event that the View subscribes to. The View then manipulates multiple screen elements based on the state within that event. For example, several buttons are made visible/hidden, or enabled/disabled, or maybe a storyboard is started.
// purely as an example:
public class SomeEvent
{
public bool ShouldShowAddButton { get; set; }
public bool ShouldShowDeleteButton { get; set; }
public bool AddButtonEnabled { get; set; }
public bool DeleteButtonEnabled { get; set; }
}
Since the VM does not know anything about the View, it can't actually reach in and do these things and instead relies on the event. Standard MVVM practice, I think. (Another option would be to make each of these items be their own published event, sent one after another.)
However, what if the VM could call into the View without knowing anything about the View?
public class MyViewModel
{
public Action OnShowAddButton { get; set; }
public Action OnShowDeleteButton { get; set; }
...etc
private void OnSomeStateChange()
{
// here, we'd normally publish the SomeEvent class
// instead, we could just call OnShowAddButton (or whatever) instead
}
}
public class MyView
{
public MyView()
{
this.myViewModel.OnShowAddButton = () => ...;
...etc
}
}
Is there a reason this would be frowned upon, other than not being "typical" of MVVM design? As far as I can tell, it's still maintaining the correct level of separation.
I think this variation is mixing a bit of MVC with a bit of MVVM, although it's none of both. So, the Model-View part of the pattern is solved in your proposal by injecting the models straight into the view implementation and then send some kind of commands, via events.
You then need to solve or go around the View-Model part of the pattern by either providing properties in the model that can be set directly by the view, or by exposing some events in the view and do the same kind of injection in the model.
I think it will get ugly. Even if the model is only a set of observable entities and you control them from somewhere else (the controller? :)).
I can already see the code, countless events and properties mixed and mingled... But it all depends on how complicated your UI will become, how many views you will have and how complex will they get. In a view with 10+ buttons and/or inputs I think is a bad idea to go with this approach.
I say that as long as you do not have a dedicated MVVM infrastructure, like WPF or HTML, there's no point in implementing your own. You can't get to that beautiful degree of separation only with a hand-coded framework. You need some support to entirely separate the UI code from the model, do bindings and so on.
Perhaps you can comment some more on what you want to use it. If you need it for a client framework (like HTML/JS) or for a Windows Forms implementation then there may be some dedicated solutions you could use, or better, some easier paths you could take.
This all comes from a guy who implemented an MVP variation on top of ASP.NET Web Forms. If I only could turn back time.

In MVVM, is every ViewModel coupled to just one Model?

In an MVVM implementation, is every ViewModel coupled to just one Model?
I am trying to implement the MVVM pattern in a project but I found that sometimes, a View may need information from multiple Models.
For example, for a UserProfileView, its UserProfileViewModel may need information from UserAccountModel, UserProfileSettingsModel, UserPostsDataModel, etc.
However, in most articles I read about MVVM, the ViewModel only consists on one Model via Dependency Injection. So the constructor takes in only one Model.
How would the ViewModel work when it has to get information from multiple Models? Or would such a situation ever occur in MVVM?
PS: I am not using the Prism or Unity Framework. I am trying to implement similar patterns into a project that I am working on which doesn't use Prism or Unity. That's why I need to understand exactly how some of these things work.
In my understanding of the MVVM pattern, the only practical requirement is that the View gets all its data from the properties of a ViewModel (probably through a binding mechanism). The ViewModel is a class that you craft specifically for that view, and takes on the responsability of populating itself as required. You could think of it like ActiveRecord for the view.
As such, it doesn't matter what you do inside the ViewModel to obtain the data that its properties should show. You could get it by querying some services, reading one or more business entity models, generating it on the spot, or all of the above. It's perfectly normal to need a combination of all these things to make a functional view.
As in any presentation pattern, the point is just to separate the process of showing some data on the screen, from the process of obtaining that data. That way you can test each part of the process separately.
Edit: Here's a small but hopefully complete example of the flow of dependencies.
// Model/service layer
public class MyModelA
{
public string GetSomeData()
{
return "Some Data";
}
}
public class MyModelB
{
public string GetOtherData()
{
return "Other Data";
}
}
// Presentation layer
public class MyViewModel
{
readonly MyModelA modelA;
readonly MyModelB modelB;
public MyViewModel(MyModelA modelA, MyModelB modelB)
{
this.modelA = modelA;
this.modelB = modelB;
}
public string TextBox1Value { get; set; }
public string TextBox2Value { get; set; }
public void Load()
{
// These need not necessarily be populated this way.
// You could load an entity and have your properties read data directly from it.
this.TextBox1Value = modelA.GetSomeData();
this.TextBox2Value = modelB.GetOtherData();
// raise INotifyPropertyChanged events here
}
}
public class MyView
{
readonly MyViewModel vm;
public MyView(MyViewModel vm)
{
this.vm = vm;
// bind to vm here
}
}
// Application layer
public class Program
{
public void Run()
{
var mA = new MyModelA();
var mB = new MyModelB();
var vm = new MyViewModel(mA, mB);
var view = new MyView(vm);
vm.Load();
// show view here
}
}
You can use multiple models in a view model. The purpose of the view model is to abstract away the business / data layer (i.e. the model).
However, using more than one model usually indicates that the view is too large. You might want to split it into user controls (which have their own view models).
a viewmodel contains the "view logic" - so all you wanna show on the view is exposed through the viewmodel. if you wanna show data from diffenrent "models" then your viewmodel agregate this and the view can bind to.
the main purpose from mvvm was btw unit test. this mean easy testing of view logic without UI.
EDIT: why do you think:
ViewModel only has one single parameter for the View in its constructor
EDIT2:
there btw two main approaches to work with mvvm, first is "View First" second is "Viewmodel First" you can of course mix up both and choose the best approach for you needs.
A ViewModel may and in many cases does use multiple Models. It is itself a "Model" of your view.
Consider a profile screen that a user enters their personal information including address. If the address is stored in an "addresses" table and the rest in a "profile" table, then the ViewModel uses both the Profile and Address models to create a unified ViewModel.
As jgauffin mentioned in his answer, many times you can use user controls to achieve a one to one relationship, but you can also introduce needless complexity by trying for this 100% of the time.
I would make sure you understand the difference between view, viewmodel, and all other model classes. The ViewModel is the model object that is filled with data that the view can be bound to. It just exists to provide data to the view, which makes the ViewModel object unit-testable, and the whole business logic separate from the view. So, you can develop your business logic entirely without using the view itself, and can replace the view with just building or using another view and binding to the ViewModel object's properties. If a view is full of empty text fields for example, the contents of the text fields can be bound to different properties of the view model.
There usually really should only be one view model. BUT if it's too complex, you can use subproperties of the bound objects like described in Binding to ViewModel.SubClass.Property (sub-property)
The ViewModel can get the data it returns to the view from a lot of different sources, business objects, databases, whatever.
Usually there is one ViewModel per Model. These ViewModels contain the logic to handle the model's data. On the other side every view has it's own view model, too. So this means:
class ModelA
{
bool TestValue{get;set;}
}
class ViewModelA<ModelA>
{
ValueViewModel<bool> TestValue{get; private set;}
public ViewModelA(ModelA model)
{
base.Model = model;
this.Initialize();
}
}
class ModelB
{
string Username;
}
class ViewModelB<ModelB>
{
ValueViewModel<string> Username{get; private set;}
public ViewModelB(ModelB model)
{
base.Model = model;
this.Initialize();
}
}
These are the ViewModels that encapsulate the models. The views have their own ViewModels:
public ViewModelForExactlyOneView
{
public ViewModelA{get;set;}
public ViewModelB{get;set;}
}
To answer your question, ViewModel1 refers to ViewModelA and ViewModelB. The View therefore can get it's data from ViewModel1.ViewModelA.TestValue.
just use the User model in your view
public partial class User : Login
{
public string Password { get; set; }
public List<Customer> customer { get; set; }
}
in this the another model login inherited and the customer model also used in this model..

Categories

Resources