user3530012
user3530012

Reputation: 740

How to have a list of models in another model?

I'm working on a desktop application and designing an MVVM pattrn. I'm keeping a list of persons with their skills. My Person model is something like:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // Other properties
}

and I have a skill class

public class Skill
{
    public string Name { get; set; }
    public bool IsOn { get; set; }
}

As you may notice each skill has a name and an IsOn property. whenever it is true it means that the person has the skill.

Now I need to know if it is ok in MVVM pattern that I have a List proeprty in my Person model? and how can I bind this list to a ListBox with Multiple selection mode? so that whenever the user clicks on an item in the ListBox, the IsOn proeprty of the selectedItem (Selected Skill) be selected or deselected?

Thanks in advance for your help.

Upvotes: 0

Views: 1011

Answers (1)

user2189331
user2189331

Reputation:

MVVM is agnostic with respect to your Model. Your model can (and will) be anything: one of your own classes, somebody else's classes, a database, a proprietary mainframe, whatever. So in answer to "if it is ok in MVVM pattern that I have a List property in my Person model?" the answer is "whatever makes sense for your model". :)

What is NOT typically okay in MVVM is to expose the model directly to the view. The view reflects the state of, binds to, and routes commands through the viewmodel, never the model. Ideally, the View knows nothing about the Model, only the ViewModel.

So let's define an intermediate set of ViewModel classes and start thinking in terms of these.

public class MainVM : ViewModelBase
{
    public ObservableCollection<PersonVM> People { get; set; }
}

public class PersonVM : ViewModelBase
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ObservableCollection<SkillVM> Skills { get; set; }
}

public class SkillVM : ViewModelBase
{
    public string Name { get; set; }
    public bool IsOn { get; set; }
}

Your View will bind to the properties on these viewmodel classes and never to properties on your model itself. Your "list of people" view will bind to the "People" collection. Your "list of skills" control will bind to the "Skills" collection. And to determine if a skill has been selected, or to select the skill, you might do something like (assuming a WPF/Silverlight-style XAML-driven view):

<DataGrid ... ItemsSource="{Binding Skills}" ... />
<DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
         <Setter Property="IsSelected" Value="{Binding IsOn, Mode=TwoWay}" />
     </Style>
</DataGrid.RowStyle>

Upvotes: 1

Related Questions