WPF - Grid - Updates row and row properties in child controls every time a new Row / Column is removed
I have a WPF Grid with XAML like this:
<Grid width=200 Height=200 >
<Grid.ColumnDefinitions >
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" MinHeight="24" />
</Grid.RowDefinitions>
<TextBlock Text="Name" Grid.Row="0" Grid.Column="0"/>
<TextBox Grid.Row="0" Grid.Column="1" />
<TextBlock Text="Age" Grid.Row="1" Grid.Column="0"/>
<TextBox Grid.Row="1" Grid.Column="1" />
</Grid>
I need to add a new row between the existing 2 rows of data, but I'm worried that when I add a new row, I will need to manually update the attached Grid.Row property on each of the controls that appear in the rows below the newly added row.
Is there a smarter way to do this? maybe to set row / column numbers relative to adjacent rows / columns?
Greetings.
This issue was addressed in Visual Studio 2010 using the Scaling Row and Column Design-Time features.
You don't have to manually update the row and column numbers manually, as Visual Studio will take care of that.
The demo below illustrates this well.
http://www.silverlight.net/learn/creating-ui/layout,-rendering,-and-panels/grid-control-design-time-row-and-column-manipulation-features
You cannot do this automatically. You have to manually adjust the Grid.Row value for each child of the grid, if needed:
foreach (UIElement child in grid.Children)
if (Grid.GetRow(child) >= indexOfNewRow)
Grid.SetRow(Grid.GetRow(child) + 1);
I found an answer in the MSDN Silverlight Forum by Jason Rosenthal:
If you hover over the left or top edge of the grid, an arrow will appear with options moved there
The link to the accepted answer now points to the generic Silverlight 5 page.
You can do this, this is the Visual Studio XAML designer, which I am illustrating with the screenshots below. This works for both WPF and Silverlight.
It is best to enlarge the Design view so you can see more clearly.
Then hover your mouse over the left edge and you will get an insertion point with a horizontal orange line indicating where the line will be inserted:
XAML before:
XAML after pasting:
Note that all Grid.Row numbers after the insertion point are automatically incremented. The row at the insertion point is automatically split in two, and the Grid.RowSpan is added to the element that was in the row at the insertion point.
In more complex layouts, automatic insertion may incorrectly add or change the Margins of elements below the insertion point, so be careful about this.