In MVVM, How to generate control dynamically?

Jan 20, 2011 at 12: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 ?

Thanks!

Jan 20, 2011 at 4:22 PM

Hi,

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 http://betaforums.silverlight.net/forums/p/48935/129554.aspx).

I hope you find this information useful.

Thanks,

Miguel Bronzovic
http://blogs.southworks.net/mbronzovic

 

Jan 23, 2011 at 1:10 AM
Edited Jan 23, 2011 at 1: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.

http://10rem.net/blog/2010/12/08/dynamically-generating-controls-in-wpf-and-silverlight

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);         
 
rootGrid.Children.Add(firstNameField);
Thanks,
Kamran