将WPF ComboBox选定项目颜色设置为ComboBox项目的颜色

时间:2012-09-12 20:53:04

标签: wpf combobox selecteditem foreground

我的组合框被绑定到状态列表。状态有一列参与,当真实时,comboitem前景颜色应为红色。这很好用。但是当我选择前景色为红色的组合框项目时,它会丢失该前景色并将其设置为黑色。有人可以帮我指出我做错了吗?

<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>

1 个答案:

答案 0 :(得分:1)

您为ComboBoxe Foreground道具设置的绑定是在可视树中查找ComboBotItem类型的祖先,但您需要的项目是{{1}的后代}}。特别是ComboBox

修改

由于您将项目绑定到模型对象,因此ComboBox.SelectedItems类型将是此模型对象类型。这意味着 - 可能 - 他们没有Foreground属性。

我建议您使用以下内容:  在我看来,DoesNotParticipate是一个布尔道具,所以不要使用ComboBoxes SelectedItem,而是使用Converter

Trigger