c# - 基于对象中枚举字段的 xaml 样式

标签 c# wpf xaml enums styles

我有一个像这样的对象集合:

public enum ObjectType
{
   Type1,
   Type2
}

public class MyObject
{
   ...
   public ObjectType ObjType;
   public string Header;
   ...
}

我从示例应用程序中获得的样式之一是:

    <Style TargetType="{x:Type inf:MyObject}">
        <Setter Property="Header" Value="{Binding Header}" />
    </Style>

如何创建受 ObjectType 枚举字段约束的单独样式? IE。对于 ObjType 设置为 Type1 和 Type2 的 MyObject 有单独的样式吗?

我的字段确实实现了 INotifyPropertyChanged,这只是一些简短的示例代码

谢谢

最佳答案

我可能会通过触发器来做到这一点:

<Style TargetType="{x:Type inf:MyObject}">
    <Setter Property="Header" Value="{Binding Header}" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding ObjType}" Value="Type1">
            <!-- A bunch of setters -->
        </DataTrigger>
        <DataTrigger Binding="{Binding ObjType}" Value="Type2">
            <!-- Another bunch of setters -->
        </DataTrigger>
    </Style.Triggers>
</Style>

分离可能是不可能的。

嗯,您可以创建单独的样式,但需要使用 ResourceKey 手动应用它们:

<Style x:Key="Type1Style" TargetType="{x:Type inf:MyObject}"
                          BasedOn="{StaticResource {x:Type inf:MyObject}}">
    <!-- Setters for type1 -->
</Style>
<Style x:Key="Type2Style" TargetType="{x:Type inf:MyObject}"
                          BasedOn="{StaticResource {x:Type inf:MyObject}}">
    <!-- Setters for type2 -->
</Style>

关于c# - 基于对象中枚举字段的 xaml 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5587093/

相关文章:

c# - 将自定义对象添加到 JObject 时出错

c# - 如何在 WPF 的 tabItem 中控制焦点

c# - 访问样式元素

c# - DateTime + long (hrs) 与 C#

c# - unity添加组件(三角形)不起作用

c# - 使用 C# 类库中的事件实现日志记录功能 - 这是好的做法吗?

wpf - 是否有任何 native WPF 多选组合框可用?

c# - 通过 XAML 绑定(bind)将静态只读值作为 CommandParameter 传递?

wpf - 删除位于标题后面的渐变样式

.net - 为每个 TabItem 重用网格行定义