Setting Grid RowDefinitions/ColumnDefinitions properties in a style
You can't define RowDefinition
and ColumnDefinition
within a style, but you can create them as reusable resources. I think this is what you're looking for. Defining a ColumnDefinitionCollection
and a RowDefinitionCollection
like so allows you to reuse them with many grids to create a consistent look.
<ResourceDictionary>
<ColumnDefinitionCollection
x:Key="MyColumnDefinitionCollection">
<ColumnDefinition
Width="50" />
<ColumnDefinition
Width="100" />
<ColumnDefinition
Width="150" />
</ColumnDefinitionCollection>
<RowDefinitionCollection
x:Key="MyRowDefinitionCollection">
<RowDefinition
Height="50" />
<RowDefinition
Height="50" />
<RowDefinition
Height="100" />
<RowDefinition
Height="100" />
</RowDefinitionCollection>
</ResourceDictionary>
<Grid
ColumnDefinitions="{StaticResource MyColumnDefinitionCollection}"
RowDefinitions="{StaticResource MyRowDefinitionCollection}">
</Grid>
I found a better and simpler solution. The answer was just adding RowDefinitionCollection tag around the RowDefinition tags.
like this:
<StackLayout>
<StackLayout.Resources>
<ResourceDictionary>
<Style TargetType="Grid">
<Setter Property="RowDefinitions">
<Setter.Value>
<RowDefinitionCollection>
<RowDefinition />
<RowDefinition />
</RowDefinitionCollection>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</StackLayout.Resources>
<Grid>
<Label Grid.Row="0" Text="(Grid #1) Row #1" />
<Label Grid.Row="1" Text="(Grid #1) Row #2" />
</Grid>
<Grid>
<Label Grid.Row="0" Text="(Grid #2) Row #1" />
<Label Grid.Row="1" Text="(Grid #2) Row #2" />
</Grid>
<Grid>
<Label Grid.Row="0" Text="(Grid #3) Row #1" />
<Label Grid.Row="1" Text="(Grid #3) Row #2" />
</Grid>
</StackLayout>
Thanks to @j.f., I found the solution. I combined his idea with mine and here is the result:
The trick was adding the declaration into a separate resource and referencing it inside style.
<StackLayout>
<StackLayout.Resources>
<ResourceDictionary>
<RowDefinitionCollection x:Key="MyRowDefinitionCollection">
<RowDefinition />
<RowDefinition />
</RowDefinitionCollection>
<Style TargetType="Grid">
<Setter Property="RowDefinitions" Value="{StaticResource MyRowDefinitionCollection}" />
</Style>
</ResourceDictionary>
</StackLayout.Resources>
<Grid>
<Label Grid.Row="0" Text="(Grid #1) Row #1" />
<Label Grid.Row="1" Text="(Grid #1) Row #2" />
</Grid>
<Grid>
<Label Grid.Row="0" Text="(Grid #2) Row #1" />
<Label Grid.Row="1" Text="(Grid #2) Row #2" />
</Grid>
<Grid>
<Label Grid.Row="0" Text="(Grid #3) Row #1" />
<Label Grid.Row="1" Text="(Grid #3) Row #2" />
</Grid>
</StackLayout>