简体   繁体   English

WPF VS2022 无法检查 targettype 是否为 Visibility

[英]WPF VS2022 cant check if targetype is Visibility

I have a IValueConverter that converts "null" to "Visible":我有一个IValueConverter将“null”转换为“Visible”:

public class InverseNullToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(System.Windows.Visibility))
            throw new InvalidOperationException("The target must be a Visibility");
        
        if (value == null)
            return Visibility.Visible;

        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

This worked fine in Visual Studio 2019 , however when i updated to 2022 i got error on every place that used this valueconverter.这在Visual Studio 2019中运行良好,但是当我更新到2022时,我在使用此值转换器的每个地方都出现错误。 The first if-case ALWAYS returns true, no matter what input is given.第一个 if-case 总是返回 true,不管输入是什么。

Why does not "if (targetType.= typeof(System.Windows.Visibility))" work in VS 2022?为什么“if (targetType.= typeof(System.Windows.Visibility))”在 VS 2022 中不起作用? What should i change to make it work?我应该改变什么才能让它工作?

Im using .Net Framework 4.7.2.我正在使用.Net Framework 4.7.2。

The error message that i receive is XDG0066 , it has no text other than the text i provide in the throw "The target must be a Visibility"我收到的错误消息是XDG0066 ,除了我在抛出的“目标必须是可见性”中提供的文本外,它没有其他文本

An example of where i used the valueconverter:我在哪里使用值转换器的示例:

<Rectangle x:Name="Back" Fill="{TemplateBinding Background}" Visibility="{TemplateBinding ImageBack, Converter={StaticResource InverseNullToVisibilityConverter}}"/>

It is a problem in the XAML designer, which seems to apply your converter in a context where the target type is not exactly Visibility .这是 XAML 设计器中的一个问题,它似乎在目标类型不完全是Visibility的上下文中应用您的转换器。

Change your check to a more generally applicable expression, like将您的检查更改为更普遍适用的表达式,例如

if (!targetType.IsAssignableFrom(typeof(Visibility)))
{
    throw new InvalidOperationException("The target must be assignable from Visibility");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM