I have the following grid in my WPF "Window" (yes the class Window);
<Grid Name="RequiredGrid"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> </Grid>
Depending on whats passed into the window, I want to add items into this grid one row at a time. Namely, I want to add a Label in the left column and a TextBox in the right column. I believe I know how to add new rows for holding new data by doing the following in the code behind:
RequiredGrid.RowDefinitions.Add(new RowDefinition());
Problem is, after I've created my Label and my TextBox.
Label AttrLabel = new Label(); TextBox AttrTextBox = new TextBox();
I don't really know how to get it into the Window so it gets displayed. I've seen some threads that say, do something like this:
this.Controls.Add(AttrLabel); this.Controls.Add(AttrTextBox);
There are two problems with this. 1) My Window class doesn't have this "Controls" property or whatever. And 2) This wouldn't help me specify the row and column of each UI item.
Now in XAML, Id be easy to specify the row and column with something like this:
<Label Grid.Column="0" Grid.Row="0"/>
This defeats the "dynamic-ness" of my intent here though. Does anyone know how I can get my dynamicaly created UI elements to display in my Window and specify which row and column it will show up in the grid.
The Grid.Row and Grid.Column properties are Attached Properties, and as such are not set like normal .net properties. The right way to set them from code is:
Grid.SetRow(someLabel, 0); Grid.SetColumn(someLabel, 0);
You should be able to do this before or after adding them to the Grid object's Children collection, but setting them before adding the control should prevent any possible flickering.
<yourGrid>
) and the Row Definitions like you have done.Create The Control (<yourcontrol>
). Then Set The ColumnSpan and Row for the Grid:
Grid.SetColumnSpan(<yourControl>, 3); Grid.SetRow(<yourControl>, 0);
Then add your control to the grid you have created
<yourGrid>.Children.Add(<yourControl>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With