3

I'm having some issues with the setup i'm currently using with my mvvm application. Having seen some posts on here, i get the feeling i may be doing this slightly wrong.

I have several models which contain lists of child models such as:

  • Project - Contains a list of proformas
  • Proforma - Contains a list of shipments orderedItems
  • Shipment - Contains a list of Containers
  • Container - Contains a list of packages

We do not have any viewmodels that relate directly to these model currently, we instead simply have viewmodels that represent the list of models, for example we have a proformalistviewmodel which simply contains a list of proformas.

My issue is, that with this setup i'm a little confused as to what viewmodel should own which data, for example the ProfomalistViewModel has a reference to the currently selected Project, all the data management for these models (the loading and saving of the list of proformas) is done via manager classes which are loaded via DI.

My question is should i instead be following what I'm seeing and having a ProjectViewModel which contains a list of proformas, and a ProformaViewModel which contains a list of shipments and ordereditems and so on.

The reason for this, is that originally none of the models we're linked, projects did not own a list of proformas they were instead loaded separately via the managers using the selected project ID (using a relational db) and we're currently changing the models to the system i described above.

5 Answers 5

5

A viewmodel should be a model of the user interaction for a particular area of functionality

For instance, if you have a project list page and the user can do certain things like delete a project, edit a project, print information about the project then you should design a viewmodel that contains the data and actions associated with this interface:

e.g. the viewmodel should contain:

 * A bindable container for the project data (list of projects)
 * Actions that handle edit/delete interaction
 * An action to handle the print functionality

The actual functionality inside these actions may not be contained within the viewmodel (the VM may have received injected services such as the print service or the project repository) but the responsibility of execution of these actions lies with the VM.

It may also be necessary to wrap each data item (project) in a viewmodel so that additional interaction dependent properties/actions can be added - such as the 'selected' property (imagine the user wants to multi-select a load of projects in the view - you could add a selected property to the ProjectViewModel which will wrap each project which makes binding easy)

You may end up with something like the following:

public class ProjectOverviewViewModel 
{
    public IList<ProjectViewModel> Projects { get;set; }

    public ProjectViewModel SelectedProject { get;set;}

    public void EditSelected() 
    {
       // Code to open edit page for the selected project
    }

    public void Print()
    {
    }
}

and the ProjectViewModel with a selectable property

public class ProjectViewModel
{
    // Either put the actual data item in here and wrap it:
    public Project Project {get;set;}

    // Or copy properties onto the viewmodel using automapper or some other mapping framework...
    // or manually :(
    // e.g. properties mirrored from the entity object:
    public int ProjectId { get;set;}
    public string ProjectName { get;set;}

    // The selected property - now your 'Selected' logic is a function of the view/viewmodel
    // not the entity. The entity should only be concerned with data persistence
    public bool IsSelected {get;set;}
}

You may also want to composite viewmodels together in order to build more complex views. Imagine you have a projects page and a "users involved in a project" page, and you wanted another page that showed both side by side (and allowed you to click a project which would refresh the users pane) - this is possible by compositing the viewmodels (by creating another viewmodel which contains the two viewmodels as properties and wires up the interaction between the two)

public class ProjectAndUserOverView
{
    public ProjectOverviewViewModel ProjectOverview {get;set;}
    public ProjectUsersViewModel ProjectUsers {get;set;}

    // Code here to listen for property changes in ProjectOverview and if SelectedProject changes
    // call ProjectUsersViewModel to refresh the data for the selected user
}

Ultimately you are just modelling the user interaction, and the more modular you can make it, the easier it will be to make cleaner more maintainable code

There are some good MVVM frameworks - my personal fave is Caliburn Micro as it makes the above very easy (it heavily uses conventions by default) and is easy to get into.

2
  • Thanks, that actually cleared some confused up, well worded and simple, also i recognize your name as having answered a number of my other questions. Thanks! p.s I'm already using caliburn.micro based on your suggestion in another question, and i love it.
    – Ben
    Nov 22, 2013 at 12:36
  • I might clear up in case anyone is confused about the 'selected' property - the SelectedProject in the ProjectOverviewViewModel would be the row the user has clicked on so that they can click the edit button, and the Selected property on the ProjectViewModel would be a 'row selector' on a grid for multi-select operations (a checkbox column for instance). Usually you would have one or the other but not both - but you could have both (SelectedItem on your Grid control bound to SelectedProject and a checkbox column against each row bound to Selected)
    – Charleh
    Nov 22, 2013 at 12:41
2

MVVM is design pattern which have 3 parts: Model, ViewModel, View. DIagram looks like this: enter image description here

http://en.wikipedia.org/wiki/Model_View_ViewModel#Pattern_description

You use ViewModels wrong. Only data for displaying should be in ViewModel. Your Model for example:

public class Project 
{
    public Proforma Pr{get;set;}
}

public class Proforma
{
    public string Name{get; set;};
}

You have View for project display(I inject ViewModel to constructor, tou can use DataContext instead):

public partial class ProjectView
{
    private ProjectViewModel vm;
    public ProjectView(ProjectViewModel vm)
    {
        this.vm = vm;
    }
}

If you want to display proforma name on Project view, you should provide it as string in ViewModel. public class ProjectViewModel { private Project pr; public string ProformaName{get{return pr.Pr.Name;}} }

If you provide Proforma like proforma, your View will know about model. It will be a violation of the pattern.

2
  • But im displaying a list of proformas in a datagrid, so the viewmodel has a Project and project has a ObservableCollection<Proforma> which the viewmodel exposes to the view, the view would never know about the model as it's simply binding to the list of models that viewmodel exposes.
    – Ben
    Nov 22, 2013 at 12:25
  • 1
    I don't totally agree with this: whilst I agree with separation, in this case the view doesn't really use the model. If you were to replace the model reference in the ViewModel with a different object, as long as it had the same properties, the bindings would still work. If you are directly affecting the model by putting code-behind into the view which directly referenced the model type, then the view/model would be coupled violating the pattern. Binding is a completely different ball-game, and creating a viewmodel for the sake of binding a couple of properties can sometimes be overkill.
    – Charleh
    Nov 22, 2013 at 13:04
1

My five cent is that MVVM is a pattern, not a religion. I use it at far as it goes and makes sense. There's many parts where MVVM is undefined (like user interaction from commands), and I read a lot about ViewModels being created just to fit MVVM (which bloats both design and object count). I would suggest you think more DataContext-wise, like "Selections of global interest are kept in a global DataContext, Proforma related data is kept in a Proforma DataContext" and so forth, where DataContext is some sort of ViewModel. In the end, you'll probably wind up rigging those up with UI.

3
  • See this is where i've always got lost, how to share global information, if im following you correctly you are suggesting having a class which contains global data for say the active proforma, and building a viewmodel that uses that?
    – Ben
    Nov 22, 2013 at 12:15
  • Yes - at least, that's what I do for practical reasons. Many parts of my apps need a selection once made (like Proforma in your case), my specific DataContexts (=VMs) have a reference to the global Data, so that I can access it everywhere. I don't know what MVVM has to say about that, but i get along pretty well that way. Nov 22, 2013 at 12:31
  • I'd consider that since a ViewModel is technically a model of a view, anything that isn't being displayed in some way isn't a viewmodel. The datacontext you describe sound more like repositories or services - something that Dependency Injection was created for. But yes, creating a ViewModel for the sake of satisfying the pattern does work, but it may add unnecessary code to your application (e.g. no point creating a viewmodel for a dropdown with a lookup data class that is only ever going to be key/value bound to the dropdown)
    – Charleh
    Nov 22, 2013 at 12:48
1

You shouldn't create ViewModels for your model objects. Generally speaking, a ViewModel should belong to a UserControl. Its role is to wire your view (your XAML) together with your model (business logic).

In your case, if I understand it correctly, you have a bunch of classes that implement business logic (Project, Shipment etc.). Your ViewModel will have access to the business logic, and provide properties for your view to bind to.

6
  • So, having a viewmodel for a datagrid (like i currently have) which contains a list of proformas makes more sense than having a viewmodel for project, which contains the list of proformas.
    – Ben
    Nov 22, 2013 at 12:12
  • @user1412240 It might be the language barrier, but I wouldn't say that you have a ViewModel "for your object". The ViewModel belongs to the View (what you display to the user). If you want to display some attributes of a Project, then your ViewModel must have access to a Project object. If you only want to display Proformas (I have no idea what that word means), then you're better off having an ObservableCollection<Proforma> property in your ViewModel.
    – Marton
    Nov 22, 2013 at 12:18
  • Marton, yes that's what i meant, profomas is simply a document that is sent for a sale of goods before the actual bill, its a "this is what you intend to buy, and how much we intend to bill you for it". The question comes tho, that ObservableCollection<Proforma> belongs to the Project model in my current setup, as proformas belong to a project, or is this bad design?
    – Ben
    Nov 22, 2013 at 12:22
  • @user1412240 No, I don't see any problem with that design. I'm just saying that if you want to display (or change) only one property of the Project (in this case, its list of Proformas), then you don't need to have a Project object in the ViewModel.
    – Marton
    Nov 22, 2013 at 12:27
  • Right, i understand your point, but that leaves me with another question of, if i dont have a project object in my viewmodel, how would i get access to that list, and not just a copy of the list.
    – Ben
    Nov 22, 2013 at 12:29
1

I do not see any problem with having view models that wrap model data objects. Viewmodels do not have to be "one per view". They can represent a row in a list or whatever.

Having said that, I am quite happy binding directly to model objects and I do it a lot. The only time I create a view model to wrap it is if I need extra state per object that is required by the view.

3
  • See that's the thing, if i was to create a viewmodel to wrap a data object, it would simply be for the sake of satisfying the pattern, and would actually have no use, as 90% of the models are only ever displayed in datagrids
    – Ben
    Nov 22, 2013 at 12:27
  • If that's the case then don't do it. The wrapping of data items isn't required, but can be useful to add additional non-entity properties such as a selected row flag or aggregated totals which don't get persisted to the data store
    – Charleh
    Nov 22, 2013 at 12:33
  • 1
    No, as per my second paragraph, only do it if you need to. There is no point doing it just to satisfy some purist MVVM pattern. Binding to the model is fine if it gives you everything you need. Nov 22, 2013 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.