wpf - WPF:绑定到字典的每个组合框项目的唯一样式
问题描述
绑定到字典(枚举,字符串)的组合框。选定的值路径是字典的Key。
是否可以为 XAML 中的每个组合框项设置单独的样式?
解决方案
在下文中,我使用了一个名为 的自定义枚举Cards
,它具有常量Skull
,Hearts
以及其他用于演示目的的枚举。您可以简单地使用您的枚举类型。
使用数据触发器的项目容器样式
您可以为每个枚举值创建一个带有触发器的项目容器样式。
<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>
推荐阅读
- javascript - 初始化前无法访问“节点”
- javascript - 当我悬停img标签以在他下方显示文本时如何制作动画
- python - Cython 魔术命令不会在 jupyter 笔记本中打印
- spring - 未找到 RestController 中的映射
- android - 此项目使用 AndroidX 依赖项,但未启用“android.useAndroidX”属性
- reactjs - React Redux - 检查ID是否存在于Reducer的状态中
- c# - Xamarin Forms 在 viewmodel 中传递参数
- python - 将字符串修剪为特殊字符
- python - 沿多通道脑电信号加速带通滤波
- apache - 将 Nginx 重写规则翻译成 Apache