如何在触发时使选定项目文本变为红色和粗体(在组合框中)

How to make selecteditem text red and bold on trigger (in combobox)

我遇到了问题:如果我从我的组合框中选择项目并且其 属性 .IsNotCorrect 为真,则将此选定项目文本设置为红色和粗体,并且组合框中的所有其他项目均为黑色。这是我尝试这样做但没有任何反应:

<ComboBox x:Name="REASON_ID" DisplayMemberPath="Name" IsReadOnly="True" IsEditable="True" 
    SelectedItem="{Binding SelectedReason, Mode=TwoWay, 
    UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">                                                   
    <ComboBox.ItemsSource>                                                        
        <CompositeCollection>
            <ComboBoxItem Content="{DynamicResource lang_Common_SelectItem}"
                          IsEnabled="False"/>
            <CollectionContainer
                 Collection="{Binding Source={StaticResource StaticReasons}}"/>

            <Style TargetType="{x:Type ComboBoxItem}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=SelectedItem.IsNotCorrect, ElementName=REASON_ID}" Value="True">
                        <Setter Property="Foreground" Value="Red" />
                        <Setter Property="FontWeight" Value="Bold" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox> 

如果需要,下拉列表中的所有项目 IsNotCorrect 都是粗体和红色,然后从显示的集合中删除您的样式并将其放入 ComboBox.Resources。绑定也要调整:

<ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsNotCorrect}" Value="True">
                <Setter Property="Foreground" Value="Red" />
                <Setter Property="FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Resources>

如果要更改文本字段中的表示,则必须修改 ComboBoxControlTemplate

  • 复制 ComboBox 的默认 ControlTemplate 请参阅 ComboBox 样式 和 模板 例如到元素的 Resources,其中包含您的 ComboBox。
  • 将复制代码中的<Style x:Key="{x:Type ComboBox}"更改为<Style x:Key="UsrDefinedStyle"
  • 找到名称为 PART_EditableTextBoxTextBox 删除复制代码中的 Style="{x:Null}"
  • ComboBox 的样式设置为 Style="{StaticResource UsrDefinedStyle}"
  • 放入您的 ComboBoxResources

    <Style TargetType="{x:Type TextBox}" BasedOn="{x:Null}">
       <Style.Triggers>
          <DataTrigger Binding="{Binding SelectedItem.IsNotCorrect, RelativeSource={RelativeSource AncestorType=ComboBox}}" Value="True">
              <Setter Property="Foreground" Value="Red" />
              <Setter Property="FontWeight" Value="Bold" />
          </DataTrigger>
       </Style.Triggers>
    </Style>