将WPF ComboBox选定项颜色设置为ComboBox项的颜色
我的组合框绑定到一个状态列表。该状态有一个列,当为true时,comboitem的前景色应为红色。这个很好用。但当我选择前景色为红色的组合框项目时,它会丢失前景色并将其设置为黑色。有人能帮我指出我做错了什么吗将WPF ComboBox选定项颜色设置为ComboBox项的颜色,wpf,combobox,selecteditem,foreground,Wpf,Combobox,Selecteditem,Foreground,我的组合框绑定到一个状态列表。该状态有一个列,当为true时,comboitem的前景色应为红色。这个很好用。但当我选择前景色为红色的组合框项目时,它会丢失前景色并将其设置为黑色。有人能帮我指出我做错了什么吗 <ComboBox Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBoxItem}},Path=Foreground}" DisplayMemberPat
<ComboBox Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBoxItem}},Path=Foreground}"
DisplayMemberPath="StateName"
ItemsSource="{Binding States}"
SelectedValue="{Binding Model.StateID}" SelectedValuePath="StateID" >
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Foreground" Value="{Binding DoesNotParticipate, Converter={StaticResource NonParticipatingConverter}}"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
您为
ComboBox
s前台
道具设置的绑定正在视觉树中寻找一个ComboBoxItem
类型的祖先,但您需要的项目是ComboxBox
的后代。尤其是组合框选择editem
编辑
由于将项绑定到模型对象,因此ComboBox.SelectedItems类型将是此模型对象类型。这意味着-可能-他们没有前景属性
我建议如下:
在我看来,DoesNotParticipate是一个布尔属性,所以不要使用转换器
,而是使用触发器
:
<ComboBox Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBoxItem}},Path=Foreground}"
DisplayMemberPath="StateName"
ItemsSource="{Binding States}"
SelectedValue="{Binding Model.StateID}" SelectedValuePath="StateID" >
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.DoesNotParticipate}" Value="True">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger
</Style.Triggers>
</Style>
</ComboBox.Style>
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Style.Triggers>
<DataTrigger Property={Binding DoesNotParticipate} Value="True">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>