Karl_Schuhmann
Karl_Schuhmann

Reputation: 1332

MVVM with Collections

If i have a model that should contain an collection e.g. book -> authors

how sould i do it

like:

public class Book
{
    public string Title { get; set; }
    public List<Author> Authors { get; set; }
}

or more like:

public class Book
{
    public string Title { get; set; }
    public List<AuthorViewModel> Authors { get; set; }
}

which of this both is the more common way to do this and how do i get the view out of the ViewModel?

Upvotes: 3

Views: 177

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273264

This one is definitely wrong:

public class Book
{
    public string Title { get; set; }
    public List<AuthorViewModel> Authors { get; set; }
}

But this would be OK:

public class BookViewModel
{
    public string Title { get; set; }
    public List<AuthorViewModel> AuthorModels { get; set; }
}

Upvotes: 4

mcalex
mcalex

Reputation: 6778

According to M-V-VM, the lower levels shouldn't know about the higher levels. The View knows of the ViewModel and databinds to its properties. The ViewModel knows about the model (and exposes properties relating to it), but doesn't know about the View.

Similarly, the Model doesn't know about the ViewModel. Therefore, a Book has Authors whereas a BookViewModel can know about Books, Authors and may even be able to invoke (through mediators) AuthorViewModels. But a Book shouldn't know about any ViewModel at all.

hth

Upvotes: 1

devdigital
devdigital

Reputation: 34349

It depends on if your models contain the properties that are sufficient to render the view. If you need to augment them with view specific code, and you don't want to pollute your models with these additional properties, then you would create a view model.

You could expose the model (Book) as a property of your view model (BookViewModel) if you wished, although purists would say you should create a wrapper property which delegates to the model for every model property.

I'm not sure what you mean by 'how do I get the view out of the view model', but if you are using the MVVM design pattern then you should be using an MVVM framework. With Caliburn.Micro for example, if you use view model first, then you would instantiate your view model and use Caliburn.Micro to locate the view and bind the two together.

Upvotes: 0

Related Questions