If you're storing a collection of CommandButton
, which is a UiElement
, in your ViewModel to bind to then you're already breaking one of the main "rules" of MVVM: no View in the ViewModel. If you want to really go the MVVM route, change your collection to some data type and then handle the setup of the UI controls (CommandButton
, Canvas
, etc.) in XAML with DataTemplates
. If you want to stick with your current direction then you might as well just create and assign the Canvas
right there with the CommandButton
creation.
What your collection data items look like all depends on what needs to be set differently on each button. If you think about creating a set of buttons manually, every property that's different across each one should be bound to a field on the data item for that button. Data can be as simple as a collection of strings. This could be used for a different raster image on each button (lots of different options for locations):
CommandButtonList = new ObservableCollection<string>
{
"http://foo.com/image1.jpg",
@"c:\images\image2.jpg",
"/ProjectImages/image3.jpg"
};
Then your ItemsControl
that binds to it would set its ItemTemplate
to something like this:
<DataTemplate>
<Button>
<Image Source="{Binding}"/>
</Button>
</DataTemplate>
Where the binding now uses the strings from the collection. This is obviously a simple example and there's lots of additional variation you can do: more complex data objects with lots of properties, more complex template with lots of bindings, multiple data templates on the same ItemsControl
by either template DataType
or a TemplateSelector
, etc.