【问题标题】:Set WPF ComboBox Selected Item Color to the Color of the ComboBox Item将 WPF ComboBox Selected Item Color 设置为 ComboBox 项的颜色
【发布时间】:2012-09-12 20:53:04
【问题描述】:

我的组合框绑定到一个状态列表。该州有一个参与的列,当它为真时,组合项前景色应为红色。这工作正常。但是当我选择前景色为红色的组合框项目时,它会失去前景色并将其设置为黑色。有人可以帮我指出我做错了什么吗?

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

【问题讨论】:

    标签: wpf combobox selecteditem foreground


    【解决方案1】:

    您为ComboBoxes Foreground 属性设置的绑定正在视觉树中寻找ComboBoxItem 类型的祖先,但您需要的项目是ComboBox 的后代。尤其是ComboBoxes SelectedItem。

    编辑

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

    我推荐以下内容: 在我看来,DoesNotParticipate 是一个布尔属性,所以不要使用Converter,而是使用Trigger:

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

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 2021-09-13
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      相关资源
      最近更新 更多