I recently came across a requirement to Programmatically Add Buttons to a WPF View in my MVVM based app. Obviously this is not entirely trivial as each Button must contain the correct Bindings to interact with the underlying ViewModel.
The way I tackled this was to use an ItemsControl, with a Canvas Control in the ItemsPanelTemplate. I then added a DataTemplate to the ItemTemplate, with our Button Template in this.
This Button Template contained the relevant binding to hook up the Command Property to my ViewModel.
For ease of use, I then created a Class which housed the various Properties I wanted to expose to each Button, such as it’s Position, CommandParameter and Content, and allowed me to return a Tickness for the Button Position.
From here I created an ObservableCollection of my new Button Class, and bound this to the ItemsControl.
The code can be seen below;