bebo
bebo

Reputation: 839

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.

Upvotes: 2

Views: 1498

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39956

You can use SharedSizeGroup property in the ColumnDefinition like this:

<ColumnDefinition SharedSizeGroup="A"/>

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

Upvotes: 4

Related Questions