Silverlight MVVM – Creating Controls Dynamically in Code-Behind or ViewModel

mvvmsilverlight

Right now I'm working migrating an app I made entirely using code behind to MVVM and had a question on where I'm supposed to be creating controls dynamically.

Basically I have a web service that returns {#} of items. For each item a button will be created and the item will be assigned to its data context.

Now so far I know that I should set the Command to the ViewModel as well as the Command property. Also I know I should call those items in my web service inside of the view model (or model, right now its irrelevant to the question). The part that is questionable is where to create the buttons.

I didn't really like the idea of creating buttons in my ViewModel since it was, well, related to the View. Is this correct or should I be creating them inside the ViewModel and then some how pass them back to the View via Messaging?

Best Answer

If the items are presented via an ItemsControl, ListBox, etc. then you can define an ItemTemplate and in that template, have a Button which binds appropriately. When Silverlight/WPF sees the object type, it'll "inflate" to what the ItemTemplate defines.

A good resource.