How to reference a row/column definition in Grid.Row/Grid.Column?
For the lulz:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Markup;
using System.Windows.Controls;
using System.Windows;
namespace Test.MarkupExtensions
{
class GridDefinitionExtension : MarkupExtension
{
public string Name { get; set; }
public GridDefinitionExtension(string name)
{
Name = name;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var refExt = new Reference(Name);
var definition = refExt.ProvideValue(serviceProvider);
if (definition is DefinitionBase)
{
var grid = (definition as FrameworkContentElement).Parent as Grid;
if (definition is RowDefinition)
{
return grid.RowDefinitions.IndexOf(definition as RowDefinition);
}
else
{
return grid.ColumnDefinitions.IndexOf(definition as ColumnDefinition);
}
}
else
{
throw new Exception("Found object is neither a RowDefinition nor a ColumnDefinition");
}
}
}
}
<Grid Width="200" Height="200"
xmlns:me="clr-namespace:Test.MarkupExtensions">
<Grid.RowDefinitions>
<RowDefinition Name="row1" />
<RowDefinition Name="row2" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="col1" />
<ColumnDefinition Name="col2" />
</Grid.ColumnDefinitions>
<Border Background="Lime" Grid.Row="{me:GridDefinition row1}" Grid.Column="{me:GridDefinition col1}" />
<Border Background="Red" Grid.Row="{me:GridDefinition row2}" Grid.Column="{me:GridDefinition col1}" />
<Border Background="Yellow" Grid.Row="{me:GridDefinition row1}" Grid.Column="{me:GridDefinition col2}" />
<Border Background="Blue" Grid.Row="{me:GridDefinition row2}" Grid.Column="{me:GridDefinition col2}" />
</Grid>
This, unfortunately, doesn't work.
The attached properties in question (ie: Grid.Row) are used by grid to handle their own layout, and the way it's designed, you have to put in the number.
Unfortunately, changing the numbers when inserting a row is pretty common in XAML development. One option - You can put in extra "zero height" rows that are unused, and later use them, if you know you're going to be adding rows.