I am trying to figure out a less messy way of repeating a control n times, depending on a bound model's property value. The first m of n controls should be displayed differently however, whereas m is bound to a different property of the ViewModel. To illustrate the problem, consider I am having a ViewModel like this (n being Display
and m Checked
here):
public class MyViewModel : ViewModelBase {
public int Display { get; set; }
public int Checked { get; set; }
/* ... */
}
For Display = 5, Checked = 3
, the view should render something along the lines of:
(X) (X) (X) ( ) ( )
Each (X)
and ( )
should be instances of the same child 开发者_开发问答view type. Now, when the user clicks on the fifth (last) control, Checked
should be set to 5 and the View would now display
(X) (X) (X) (X) (X)
Now I could achieve this by hooking up a few event handlers and programmatically adding and binding ( )
instances whenever Display
changes. I do wonder though if there is a more concise, lessy messy method to achieve this.
Think of the ViewModel as a model of the View. So if you want to show a collection of items in the view you have to provide that collection on the ViewModel.
In this case add a collection to the ViewModel that changes when the value for Display and Checked changes. Then bind an ItemsControl to the collection and provide an ItemTemplate for the items.
精彩评论