Click here to Skip to main content
14,668,844 members
Rate this:
Please Sign up or sign in to 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.

Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   
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)
Rate this:
Please Sign up or sign in to vote.

Solution 2

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);
           }
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

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.
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100