【问题标题】:WPF Combobox: Multiple Column WidthWPF 组合框:多列宽
【发布时间】: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>

谢谢。

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    为列创建SharedSizeGroup(替换&lt;ColumnDefinition Width="225"/&gt;

    <ColumnDefinition Width="Auto" SharedSizeGroup="FirstColumn"/>
    

    并在 ComboBox 上启用SharedSizeScope

    <ComboBox x:Name="CommandListComboBox" Grid.IsSharedSizeScope="True" ...
    

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多