Is it possible to use a Grid as a container for elements with a DataTemplate ? And if not, then how to give the width of the first column of all Grid located in the StackPanel (preferably via Binding )

An example of my xaml:

 <ItemsControl> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Vertical"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid.Children> <TextBlock Grid.Column="0" Text="{Binding Path=NameRow}"/> <TextBox Grid.Column="1" Text="{Binding Path=Value1}"/> <Button Grid.Column="2" Content="Test"/> </Grid.Children> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 

As you can see, the first column is a Binding to the NameRow property, but if the rows are of different lengths, then the elements float depending on the NameRow . How would you align them along the maximum length of the first column of all the Grid ?

    1 answer 1

    If I understand correctly, you need to align the columns located in different Grid . Below is an abstract example that shows how to solve this:

     <ItemsControl Grid.IsSharedSizeScope="True" ItemsSource="{Binding MyItems}"> <ItemsControl.Resources> <DataTemplate DataType="{x:Type Models:MyFirstModelType}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="Description" /> <ColumnDefinition SharedSizeGroup="Value" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" Content="{Binding Description}" /> <Slider Grid.Column="1" Value="{Binding Value}" /> </Grid> </DataTemplate> <DataTemplate DataType="{x:Type Models:MySecondModelType}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="Description" /> <ColumnDefinition SharedSizeGroup="Value" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" Content="{Binding Description}" /> <Slider Grid.Column="1" Value="{Binding Value}" /> </Grid> </DataTemplate> </ItemsControl.Resources> </ItemsControl> 

    The key point to pay attention to is:

    1) The SharedSizeGroup SharedSizeGroup , the value of which is a matching string. Columns with the same match string will be aligned the same.

    2) The Grid.IsSharedSizeScope property, which must be set to true order for the whole thing to work.

    • Yes, everything worked fine, even if there are several controls from this template on the form! Thank! - Dmitry Chistik
    • Always, please) - sp7