In MVVM, How to generate control dynamically?

Jan 20, 2011 at 1:56 AM

This is my situation: A Textbox for typing an number, click button "OK" , the page will generate many Textboxes according to the number typed. That's very easy in Code Behind.

How to implement this in MVVM ?


Jan 20, 2011 at 5:22 PM


As Prism´s Chapter 5: Implementing the MVVM Pattern documentation shows:

…because the view model should have no explicit knowledge of the specific visual elements in the view, code to programmatically manipulate visual elements within the view should reside in the view's code-behind or be encapsulated in a behavior. Similarly, code to retrieve or manipulate data items that are to be displayed in the view through data binding should reside in the view model.

Therefore, your code regarding on the creation the textboxes could reside in view´s code behind, but the code to retrieve or manipulate the data to be shown in those textboxes should reside in the view model. In order to achieve that, you should take into account that you can create bindings programatically (you can see an example here

I hope you find this information useful.


Miguel Bronzovic


Jan 23, 2011 at 2:10 AM
Edited Jan 23, 2011 at 2:11 AM

The text box should be created in the code behind. The data model it binds to should be in the view model as in the below link.

So you would have code like this in the cod behind, which binds to a view model:


var firstNameField = CreateTextBox(new Thickness(3), 0, 1);
Binding firstNameBinding = new Binding();
firstNameBinding.Source = viewModel;
firstNameBinding.Path = new PropertyPath("FirstName");
firstNameBinding.Mode = BindingMode.TwoWay;
firstNameField.SetBinding(TextBox.TextProperty, firstNameBinding);