Reputation: 4056
I have a ListBox with four columns, placed into the second row of my grid which also contains 4 columns. I use the Main grid's ColumnDefinitions to place four titles above the ListBox, and I need the ListBox that I have placed in row 1 of the Main Grid to have ColumnWidths that match according to the titles I've created.
<Grid Margin="12,0,12,6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="One" Grid.Row="0" Grid.Column="0"/>
<TextBlock Text="Two" Grid.Row="0" Grid.Column="1"/>
<TextBlock Text="Three" Grid.Row="0" Grid.Column="2"/>
<TextBlock Text="Four" Grid.Row="0" Grid.Column="3"/>
<ListBox x:Name="HistoryListBox" Grid.Row="1" Grid.ColumnSpan="4">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width*"/>
<ColumnDefinition Width*"/>
<ColumnDefinition Width*"/>
<ColumnDefinition Width*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding One}"/>
<TextBlock Grid.Column="1" Text="{Binding Two}"/>
<TextBlock Grid.Column="2" Text="{Binding Three}"/>
<TextBlock Grid.Column="3" Text="{Binding Four}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
All I see in my ListBox is jumbled data that is not separated into the proper column widths to match the TextBoxes above. How can I fix this?
Upvotes: 1
Views: 586
Reputation: 58
When you use ListBox.ItemTemplate it means that you have a grid for each item of your listBox.
If you use the * on each column you get the available space equally divided to the columns but you still have a different grid for each element.
I would suggest using a Grid instead the ListBox or use the SharedSizeGroup properties if you insist with the Listbox.ItemTemplate approach and you will be able to have different sizes for each column and still maintain the 'illusion' of a grid.
Upvotes: 0
Reputation: 3683
Maybe this is enough
<ListBox x:Name="HistoryListBox" Grid.Row="1" Grid.ColumnSpan="4">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding One}"/>
<TextBlock Grid.Column="1" Text="{Binding Two}"/>
<TextBlock Grid.Column="2" Text="{Binding Three}"/>
<TextBlock Grid.Column="3" Text="{Binding Four}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Upvotes: 1