【问题标题】:How to set Combobox dropdown list width to the Combobox it belongs to?如何将 Combobox 下拉列表宽度设置为其所属的 Combobox?
【发布时间】:2019-04-01 14:29:29
【问题描述】:

见下图,下拉列表边框如何与实际组合框对齐?

https://imgur.com/uNO45F2

这里是 Combobox 的代码,它使用自定义的 ComboBoxItem 样式,

<ComboBox Grid.Row="0" Grid.Column="0" ItemsSource="{Binding ASDevicesView, Mode=OneWay , UpdateSourceTrigger=PropertyChanged}"  AutomationProperties.AutomationId="4314"
                      SelectedItem="{Binding SDevice}" IsEditable="True" Text="{Binding SearchText}" MaxDropDownHeight="166" ItemContainerStyle="{StaticResource MyComboBoxItemStyle}">
    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="IsDropDownOpen" Value="true" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

这里是 ComboBoxItem 样式的代码,

<Style x:Key="MyComboBoxItemStyle" BasedOn="{StaticResource {x:Type ComboBoxItem}}" TargetType="{x:Type ComboBoxItem}">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="RenderOptions.ClearTypeHint" Value="Enabled" />
    <Setter Property="Width" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}" />
    <Setter Property="Height" Value="40" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ComboBoxItem">
                <Grid Background="Transparent" >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="36"/>
                        <ColumnDefinition Width="AUTO"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="AUTO"/>
                    </Grid.RowDefinitions>
                    <Image Source="{Binding Icon}" Width="12" Height="12" Margin="3,3,3,3" Grid.Row="0" Grid.Column="0"/>
                    <TextBlock Text="{Binding DName}" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left"  VerticalAlignment="Center" FontWeight="Bold"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

【问题讨论】:

  • 如果这样做,您可能会截断项目的文本
  • 是的,我知道,但没关系,我只想将下拉列表与组合框对齐

标签: c# wpf user-interface


【解决方案1】:

我认为问题在于ComboBox 不是ComboBoxItemTemplatedParent(确实在此comment 中已指出),因此最好明确搜索:

<Setter Property="Width" Value="{Binding 
    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=ActualWidth}" />

【讨论】:

    猜你喜欢
    • 2014-04-07
    • 2011-08-17
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多