按类而不是属性设置WPF格式

本文关键字:设置 WPF 格式 属性 | 更新日期: 2023-09-27 18:30:43

是否可以按类类型将格式应用于 WPF 控件。假设我有一个包含五个子类的类,我想根据启动的子类给出不同的颜色。是否可以绑定到类并按子类类型进行区分,还是必须设置要绑定到的子类特定属性?

目前,我绑定到的每个子类中都有一个字符串属性,我使用转换器返回正确的画笔。我想知道通过查看类类型是否有更优雅的方法。

按类而不是属性设置WPF格式

可以将 ContentControl 绑定到对象,为每个子类创建不同的 DataTemplate。假设要显示的控件是一个按钮,那么它将是这样的。

<ContentControl Content={Binding ...}>
    <ContentControl.Resources>
        <DataTemplate DataType={x:Type local:Subclass1}>
            <Button Background="Red"/>
        </DataTemplate>
        <DataTemplate DataType={x:Type local:Subclass2}>
            <Button Background="Blue"/>
        </DataTemplate>
        ...
    </ContentControl.Resources>
</ContentControl>

对于您的情况来说,这似乎是一个沉重的解决方案,但这种结构经常派上用场!

您可以将 color 属性绑定到实例并编写一个转换器,该转换器将为不同类型的返回不同的 Brush:

Background={Binding Converter={c:InstanceToColorConverter}},

在 InstanceToColorConverter 的转换方法中,如果语句级联可以实现

if(value is A)return new SomeBrush();else 
   if(value is B)return new AntoherBrush();

您还可以创建类Attribute,用于存储首选画笔颜色并在转换方法中检测其值,例如:

value.GetType().GetCustomAttributes(false).First(x=>x is ColorAttribute).Color

通常的方法是为 XAML 中的每个子类设计数据模板。但是,是的,您也可以绑定到子类类型。

在基本数据库中,提供 .Net 类型:

public Type MyType
    {
        get
        {
            return GetType();
        }
    }

在 MyType 上的 Xaml 触发器中,子类将继承它:

<DataTrigger Binding="{Binding MyType}" Value="{x:Type myNamespace:MySubClass1}">
    <Setter ../>
</DataTrigger>
<DataTrigger Binding="{Binding MyType}" Value="{x:Type myNamespace:MySubClass2}">
    <Setter ../>
</DataTrigger>

我做了以下解决方案:

<Grid Background = "{Binding Converter={StaticResource Myconverter} />

这会使用网格所在的数据上下文传递我的类对象。

然后,我使用转换器检查类类型并返回相应的颜色画笔。