set global row definitionin wpf grid

245 views Asked by At

I have a grid with two labels.

<Grid>
    <Label Grid.Row="0" Content="Hello" Height="20"></Label>
    <Label Grid.Row="1" Content="World" Height="20"></Label>
</Grid>

I know that I can add for each row, but if I have 100 rows I need to add 100 rows definitions. Is there a way to globally set the row definitions so that all rows/columns will inherited their property?

1

There are 1 answers

0
McGarnagle On

You could always subclass Grid. Set each child's Grid.Row property, and add the row definitions, manually when the control loads. You could add a property to the control to specify a uniform height for each row. For example:

public class UniformGrid : Grid
{
    public double? UniformHeight { get; set; }

    public UniformGrid()
    {
        Loaded += UniformGrid_Loaded;
    }

    void UniformGrid_Loaded(object sender, RoutedEventArgs e)
    {
        int i=0;
        foreach (FrameworkElement child in Children)
        {
            var rowHeight = UniformHeight.HasValue ? new GridLength(UniformHeight.Value) : GridLength.Auto;
            RowDefinitions.Add(new RowDefinition { Height = rowHeight });
            Grid.SetRow(child, i++);
        }
    }
}

Usage:

<my:UniformGrid UniformHeight="20">
    <Label Content="Hello" />
    <Label Content="World" />
</my:UniformGrid>

(Although, as some comments pointed out, the above is basically just a StackPanel only slower.)