How to reference a row/column definition in Grid.Row/Grid.Column?

Viewed 6673

This may be obvious... How do I reference XAML elements later in that same XAML file?

Example:

<Grid.RowDefinitions>
    <RowDefinition Height="661*" Name="someGridRow" />
    <RowDefinition Height="230*" Name="someOtherGridRow"/>
</Grid.RowDefinitions>

Then I define various controls inside the grid and I'd like to reference these rows by name, not by number:

<RichTextBox Grid.Row="someGridRow" ... />

Because if I use Grid.Row="0" on many controls, then when I add a row before the first row, I have to change all the references to Grid.Row="1" by hand.

EDIT:

Thanks to the answers I have been reading a bit on XAML.

After all, it IS possible to reference a previous element by name apparently:

Grid.Row="{Binding ElementName=someGridRow}"

or

Grid.Row="{x:Reference someGridRow}"

but this doesn't solve the problem entirely because Grid.Row requires an int, whereas someGridRow is not an int, it's a System.Windows.Controls.RowDefinition.

So what is needed is the XAML equivalent of

Grid.Row = grid.RowDefinitions.IndexOf(someGridRow)

which in code behind would be written

Grid.SetRow(richTextBox, grid.RowDefinitions.IndexOf(someGridRow))

or do a binding of Grid.Row to the property, on the object grid, which has the path "RowDefinitions.IndexOf" with the parameter someGridRow:

PropertyPath path = new PropertyPath("RowDefinitions.IndexOf", someGridRow);
Binding binding = new Binding() { ElementName = "grid", Path = path };
richTextBox.SetBinding(Grid.RowProperty, binding);

(this actually doesn't work in C#, so I must be doing something wrong, although Grid.SetRow above does work)

XAML 2009 defines <x:Arguments> to invoke constructors which have parameters. If that worked in WPF XAML, then something like that would work I suppose?

<Grid.Row>
  <Binding ElementName="grid">
    <Binding.Path>
      <PropertyPath>
        <x:Arguments>
          RowDefinitions.IndexOf
          <Binding ElementName="someGridRow"/>
        </x:Arguments>
      </PropertyPath>
    </Binding.Path>
  </Binding>
</Grid.Row>

where <Binding ElementName="someGridRow"/> can also be replaced by <x:Reference Name="someGridRow"/> in XAML 2009.

3 Answers

Another way to get the Grid.Column would be binding to the ViewModel like this:

<TextBlock Text="Nummer: " Grid.Column="{Binding Cols.C1}" />

In the ViewModel:

public ColumnDefs Cols { get; }

And finally the definition of your ColumnWidth values:

public class ColumnDefs
{
    public int C1 => 0; // or however you retrieve the columns index
    public int C2 => 1;
}

Know, if you have to insert columns (works with rows also), you just have to change the index values in your ViewModel. This approach should be less exhaustive than changing every Grid.Column attribute in your xaml.

Related