首页 > 解决方案 > WPF:绑定到字典的每个组合框项目的唯一样式

问题描述

绑定到字典(枚举,字符串)组合框。选定的值路径是字典的Key

是否可以为 XAML 中的每个组合框项设置单独的样式?

标签: wpfxamlbindingstyles

解决方案


在下文中,我使用了一个名为 的自定义枚举Cards,它具有常量SkullHearts以及其他用于演示目的的枚举。您可以简单地使用您的枚举类型。

使用数据触发器的项目容器样式

您可以为每个枚举值创建一个带有触发器的项目容器样式。

<Style x:Key="EnumComboBoxItemStyle"  TargetType="{x:Type ComboBoxItem}">
   <Style.Triggers>
      <DataTrigger Binding="{Binding Key}" Value="{x:Static local:Cards.Skull}">
         <Setter Property="Foreground" Value="Blue"/>
      </DataTrigger>
      <DataTrigger Binding="{Binding Key}" Value="{x:Static local:Cards.Hearts}">
         <Setter Property="Foreground" Value="Red"/>
      </DataTrigger>
   </Style.Triggers>
</Style>
<ComboBox ItemContainerStyle="{StaticResource EnumComboBoxItemStyle}" ...>

项目容器样式选择器

如果您有多种不同的样式,另一种选择是创建样式选择器,如下所示:

<Style x:Key="SkullComboBoxItemStyle" TargetType="{x:Type ComboBoxItem}">
   <Setter Property="Foreground" Value="Green"/>
</Style>
<Style x:Key="HeartsComboBoxItemStyle" TargetType="{x:Type ComboBoxItem}">
   <Setter Property="Foreground" Value="Red"/>
</Style>
<!-- ...other styles. -->

样式选择器根据枚举值确定样式。

public class CardsKeyStyleSelector : StyleSelector
{
   public override Style SelectStyle(object item, DependencyObject container)
   {
      if (container is FrameworkElement element && item is KeyValuePair<Cards, string> keyValuePair)
      {
         switch (keyValuePair.Key)
         {
            case Cards.Skull:
               return element.FindResource("SkullComboBoxItemStyle") as Style;
            case Cards.Hearts:
               return element.FindResource("HeartsComboBoxItemStyle") as Style;
            // ...other cases.
         }
      }

      return null;
   }
}

您可以将样式选择器分配给组合框,它将选择正确的样式。

<ComboBox ...>
   <ComboBox.ItemContainerStyleSelector>
      <local:CardsKeyStyleSelector/>
   </ComboBox.ItemContainerStyleSelector>
</ComboBox>

推荐阅读