darthwillard
darthwillard

Reputation: 819

WPF how to change label of property from dynamic object in MVVM

I have a program that when you click the button, it creates a person with random attributes.

enter image description here

If the content of the label changes with every different object (person) created, how do you define that in true MVVM style? I can't have the viewmodel control the view, right? So i can't

label.Content = person.hair_Color;

public class Person() 
    get set hair_Color, get set shirt_color, yadda yadda

Because there can be either 1 or an infinite amount of people, how do i dynamically add the content of a label, if i don't know how many there will be?

Upvotes: 0

Views: 1642

Answers (1)

Kilazur
Kilazur

Reputation: 3188

In 'true MVVM style', you would have something like:

Views

MainView containing:

  • A button "Add Person" <Button Command={Binding AddPerson}/>
  • A list containing some "PersonView" <ListBox ItemsSource="{Binding Persons}"/>

PersonView containing:

  • A label "Shirt" <TextBlock Text="{Binding Shirt}"/>
  • A label "Hair" <TextBlock Text="{Binding Hair}"/>
  • A rectangle (for the example) "ShirtGraphic" <Rectangle Background="{Binding Shirt, Converter={stringToColorConverter}/>
  • A rectangle "HairGraphic" <Rectangle Background="{Binding Hair, Converter={stringToColorConverter}/>

StringToColorConverter class, returning a color from a string

ViewModels

MainViewModel containing:

  • An observable collection property of PersonViewModel "Persons" public ObservableCollection<PersonViewModel> Persons { get; set; }
  • A command "AddPerson" public Command AddPerson { get; set; }

PersonViewModel containing:

  • A string property "Shirt" public string Shirt { get; set; }
  • A string property "Hair" public string Hair { get; set; }

This is pretty much just a mockup of what you would actually have, since implementation depends on the framework used, but the idea is here. You bind, you convert, etc.

  • It doesn't implement any INotifyPropertyChanged or ICommand
  • No DataTemplate is set for the ListBox (to actually display some PersonView)

Upvotes: 3

Related Questions