Click here to Skip to main content
15,884,721 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a WPF Window, and in that window I have a grid.

I use M-V-VM model and I want to add a TextBox to the grid dynamically in code(in viewmodel)

How can I get access to the grid?
Posted
Updated 1-Nov-10 22:39pm
v2
Comments
Dalek Dave 2-Nov-10 4:39am    
Edited for Grammar, Syntax and Readability.

As I understand MVVM, you shouldn't access view (or UI elements) directly from view model (or another layer below UI). If you need something like this, you should do it in view layer only.
 
Share this answer
 
Comments
Dalek Dave 2-Nov-10 4:39am    
Good Answer.
Martin.Smith 9-Nov-10 11:19am    
Completely agree - ViewModel should not know anything about the view (or the controls it contains)
I write it
Grid grid = new Grid();
           grid = App.Current.Windows[1].FindName("grid1") as Grid;
           if (grid != null)
           {
               RowDefinition rd = new RowDefinition();
               rd.Height = GridLength.Auto;
               grid.RowDefinitions.Add(rd);
               TextBox txt = new TextBox();
               txt.Name = "txtNewAdd";
               txt.Height = 23;
               txt.VerticalAlignment = VerticalAlignment.Top;

               //txtFname is in view Layer
               TextBox txtName = new TextBox();
               txtName= grid.FindName("txtFname") as TextBox;
               if (txtName!=null)
               {
                   txt.Background = txtName.Background ;

               }
               Grid.SetColumn(txt, 1);
               Grid.SetRow(txt,(grid.RowDefinitions.Count-1));

               grid.Children.Add(txt);
           }
 
Share this answer
 
v2
While probably not optimal given the MVVM best practices, you could have an ObservableCollection(Of UIElement) to which the Grid or ItemsControl is bound.

Your ViewModel or Model would create the new control and add it to the collection.
 
Share this answer
 
Comments
fjdiewornncalwe 7-Jan-13 12:04pm    
Please check the date that a question was posted on. The chances that the OP is still looking for a solution from over two years ago is highly unlikely, and the question already has two solution posted. If the question is this old, please don't add new answers to it as it just bumps it back to the front of the queue which it shouldn't be doing. Cheers and welcome to CP.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900