views:

88

answers:

1

Hi

I have a ListBox that is bound to a list of Persons. I want to show the items of the listbox in a grid. I can accomplish this with the code below, but the problem is that with this code each item has its own grid. I want one grid to contain all items so that each column in the grid is automatically scaled to the width of the longest string. I suppose I should bind data to a Grid in stead? How?

<ListBox ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition />
          <ColumnDefinition />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="{Binding Path=Name}" />
        <TextBlock Grid.Column="1" Text="{Binding Path=Age}" />
        <TextBlock Grid.Column="2" Text="{Binding Path=Gender}" />
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
+1  A: 

You can still accomplish this using the Grid inside of your DataTemplate. You would just need to specify the IsSharedSizeScope attached property on your ListBox and SharedSizeGroup property on the ColumnDefinitions you want to synchronize.

Alternatively you can define the ListBoxes' panel as a Grid, but I don't recommend that unless your Person objects have an ordering property which can be used easily to bind to Grid.Row.

micahtan