Reputation: 743
I have a ComboBox in WPF that contains multiple columns for the list section. Everything works fine as long as I explicitly specify the width of the columns. If I specify "auto" for the width of the first column the grid structure breaks down and columns of each row are not aligned with each other. What I would like is the ability for the first column to be as wide as it needs to be in order to fix the text for the longest row, and the other column to fill the rest of the available space.
My XAML is below:
<ComboBox x:Name="CommandListComboBox" Margin="95,0.48,110,30" ItemsSource="{Binding}" HorizontalContentAlignment="Stretch" SelectionChanged="CommandListComboBox_OnSelectionChanged" IsEditable="True" IsReadOnly="True" DisplayMemberPath="Description">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid x:Name="gd" TextElement.Foreground="Black" Width="{Binding Path=ActualWidth,ElementName=CommandListComboBox}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="225"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Margin="5" Grid.Column="0" Text="{Binding Description}" TextWrapping="Wrap"/>
<TextBlock Margin="5" Grid.Column="1" Text="{Binding DeviceListText}" TextWrapping="Wrap"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="ListBoxItem.IsSelected" Value="True">
<Setter TargetName="gd" Property="Background" Value="Gray"/>
<Setter TargetName="gd" Property="TextElement.Foreground" Value="White"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="gd" Property="Background" Value="Blue"/>
<Setter TargetName="gd" Property="TextElement.Foreground" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
Thanks.
Upvotes: 0
Views: 1212
Reputation: 35646
create a SharedSizeGroup
for columns (replacement for <ColumnDefinition Width="225"/>
)
<ColumnDefinition Width="Auto" SharedSizeGroup="FirstColumn"/>
and enable SharedSizeScope
on ComboBox:
<ComboBox x:Name="CommandListComboBox" Grid.IsSharedSizeScope="True" ...
Upvotes: 2