首页 > 解决方案 > WPF 转换器值类型始终为“RuntimeType”

问题描述

我正在尝试Button根据 中选择的值更改 的可见性ComboBox

ComboBox数据源是List<Type>

<ComboBox ItemsSource="{Binding Objects}" SelectedItem="{Binding SelectedObject}" 

按钮绑定如下:

<Button Visibility="{Binding SelectedObject, Converter={StaticResource TypeToVisibilityConverter}, Mode=TwoWay}"/>

TypeToVisibilityConverter:

public class TypeToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;

        if (value is CmQuote)
            return Visibility.Visible;
        else
            return Visibility.Hidden;
    }
}

由于某种原因,当在CmQuote中选择类型时ComboBoxvalue名称是正确的,即CmQuote,但实际类型是RuntimeType而不是 CmQuote,因此总是使 if 语句为 false。

我也试过做typeof(value)value.GetType() == typeof(CmQuote)

如何将类型传递给此转换器,并在运行时检查它是否为特定类型?

编辑:添加这样的对象:

    private void InitializeObjects()
    {
        foreach (var assemblyName in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
        {
            if (assemblyName.Name == "cmFIX")
            {
                Assembly assembly = Assembly.Load(assemblyName);

                foreach (var type in assembly.GetTypes())
                {
                    if (type.Name.Substring(0, 2) == "Cm")
                    {
                        Objects.Add(type);
                    }
                }
            }
        }

        Objects.Add(typeof(string));
    }

标签: c#wpfbindingconverters

解决方案


value在转换器中收到的是类型,而不是任何类型的实例。所以GetType()返回RuntimeType

进行强制转换并将 Type 与由typeof()运算符获得的另一个 Type 进行比较:

public class TypeToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Type t = value as Type;

        if (t == typeof(CmQuote))
            return Visibility.Visible;

        return Visibility.Hidden;
    }
}

推荐阅读