bebo bebo - 24 days ago 7
C# Question

WPF ListBox Layout (dynamic column width considering all rows at once)

Is there a way to make sure that the

Width="auto"
property considers the
Width
of all elements in a list instead of calculating it individually for every row in the list?

<ListBox x:Name="listBox" HorizontalContentAlignment="Stretch" DockPanel.Dock="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" />
<TextBlock Grid.Column="1" Text="{Binding Value}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>


I tried this, but as the length of the
Name
is different for each column, the
Width
of the
Name
column of every row is different. Thus the second column starts at a different x position.

Answer

You can use SharedSizeGroup property in the ColumnDefinition like this:

<ColumnDefinition SharedSizeGroup="A"/>

Also have a look at this: Grid Size Sharing in WPF.

Comments