SharedSizeGroup
SharedSizeGroup
allows sharing size information for autosized row and column definitions across multiple Grid
controls.
Example
The following example demonstrates how SharedSizeGroup
can be used to consistently size columns within a ListBox
and outside.
- XML
- C#
<StackPanel Grid.IsSharedSizeScope="True">
<StackPanel.Styles>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="0" />
</Style>
</StackPanel.Styles>
<ListBox ItemsSource="{Binding People}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Name="myGrid" RowDefinitions="auto, auto" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A" />
<ColumnDefinition SharedSizeGroup="B" />
<ColumnDefinition Width="*" />
<ColumnDefinition SharedSizeGroup="C" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="6,0" Text="{Binding FirstName}" />
<TextBlock Grid.Column="1" Margin="6,0" Text="{Binding LastName}" />
<TextBlock Grid.Column="2" Margin="6,0" Text="{Binding Age}" />
<TextBlock Grid.Column="3" Margin="6,0" Text="{Binding Occupation}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- Controls may appear in-between Grids with SharedSizeGroups -->
<Separator />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A" />
<ColumnDefinition SharedSizeGroup="B" />
<ColumnDefinition Width="*" />
<ColumnDefinition SharedSizeGroup="C" />
</Grid.ColumnDefinitions>
<Button Content="This is the First Name" HorizontalAlignment="Stretch" Grid.Column="0" />
<Button Content="Last" HorizontalAlignment="Stretch" Grid.Column="1" />
<Button Content="Age" HorizontalAlignment="Stretch" Grid.Column="2" />
<Button Content="Occupation" HorizontalAlignment="Stretch" Grid.Column="3" />
</Grid>
</StackPanel>
public record Person(string FirstName, string LastName, int Age, string Occupation);
public partial class MainWindowViewModel : ViewModelBase
{
public ObservableCollection<Person> People { get; } = new()
{
new("Jim", "Smith", 35, "Printed Circuit Board Drafter"),
new("Charlotte", "O'Shaughnessy-Alejandro", 30, "Librarian"),
new("Ryan", "Cullen", 40, "Ceramics Instructor"),
new("Valentina", "Levine", 38, "Oceanologist")
};
}
![](/assets/images/grid-sharedsizegroup-954b77979bc1714b0bb5ef180b342f58.png)
Notice how each column is sized: the first column is sized by the Button
, the second and fourth are sized
by the ListBox
content, and the third takes the remaining space.