【发布时间】:2018-03-01 14:12:21
【问题描述】:
我在 WPF 中有一个 ComboBox,其中包含列表部分的多个列。只要我明确指定列的宽度,一切正常。如果我为第一列的宽度指定“自动”,则网格结构会分解,并且每行的列彼此不对齐。我想要的是第一列能够尽可能宽,以便修复最长行的文本,另一列填充剩余的可用空间。
我的 XAML 如下:
<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>
谢谢。
【问题讨论】: