问题
I faced the problem: if I choose item from my combobox and its property .IsNotCorrect is true then make this selecteditem text red and bold and all other items in combobox are black. This is my attempt of doing this but nothing happens:
<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>
回答1:
If you want, that all items in drop down list, which IsNotCorrect are bold and red, then remove your Style from displayed collection and put it to the ComboBox.Resources. The binding should also be adjusted:
<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>
If you want to change the representation in text field, then you have to modify the ControlTemplate of ComboBox.
- copy the default
ControlTemplateof ComboBox see ComboBox Styles and Templates e.g. to theResourcesof element, which contains your ComboBox. - Change the
<Style x:Key="{x:Type ComboBox}"to the<Style x:Key="UsrDefinedStyle"in the copied code. - Find
TextBoxwith namePART_EditableTextBoxand removeStyle="{x:Null}"in the copied code. - Set style of your
ComboBoxto theStyle="{StaticResource UsrDefinedStyle}" Put to the
Resourcesof yourComboBox:<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>
来源:https://stackoverflow.com/questions/60221731/how-to-make-selecteditem-text-red-and-bold-on-trigger-in-combobox