基于对象类型的 WPF 触发器 [英] WPF Trigger based on Object Type

查看:36
本文介绍了基于对象类型的 WPF 触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法对触发器的对象类型进行比较?

Is there a way to do a comparison on object type for a trigger?

<DataTrigger Binding="{Binding SelectedItem}" Value="SelectedItem's Type">
</DataTrigger>

背景:我有一个工具栏,我想根据当前设置为所选项目对象的子类隐藏按钮.

Background: I have a Toolbar and I want to Hide button's depending on what subclass is currently set to the selected item object.

谢谢

推荐答案

为什么不直接使用一个转换器来接受一个对象并返回一个对象类型的字符串?

Why not just use a converter that takes an object and returns a string of the object type?

Binding="{Binding SelectedItem, Converter={StaticResource ObjectToTypeString}}"

并将转换器定义为:

public class ObjectToTypeStringConverter : IValueConverter
{
    public object Convert(
     object value, Type targetType,
     object parameter, System.Globalization.CultureInfo culture)
    {
        return value.GetType().Name;            
    }

    public object ConvertBack(
     object value, Type targetType,
     object parameter, System.Globalization.CultureInfo culture)
    {
        // I don't think you'll need this
        throw new Exception("Can't convert back");
    }
}

您需要在 xaml 中的某处声明静态资源:

You'll need to declare the static resource somewhere in your xaml:

<Window.Resources>
    <convs:ObjectToTypeStringConverter x:Key="ObjectToTypeString" />
</Window.Resources>

在这种情况下,'convs' 是转换器所在的命名空间.

Where 'convs' in this case is the namespace of where the converter is.

希望这会有所帮助.

这篇关于基于对象类型的 WPF 触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆