WPF Converter强制转换导致Visual Studio设计器异常 [英] WPF Converter casting causes Visual Studio designer exception

查看:92
本文介绍了WPF Converter强制转换导致Visual Studio设计器异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示的转换器将导致2008 Visual Studio设计器不显示xaml,并且出现错误指定的转换无效".

A converter such as what follows will cause the 2008 visual studio designer to not display the xaml, and error out with a "Specified cast is not valid." exception.

public class ItemsVisibilityToGridColumnWidthConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        //THE TWO OFFENDING LINES...
        var itemsVisibility = (Visibility)values[0];
        var orientation = (Orientation)values[1];

        if (orientation == Orientation.Horizontal && itemsVisibility != Visibility.Visible)
        {
            return new GridLength(0);
        }

        return new GridLength(4, GridUnitType.Star);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

更改演员表以使用诸如此类的方法即可解决此问题:

Changing the cast to use a method such as this fixes the issue:

static class EnumCaster
{
    internal static Orientation CastAsOrientation(object value)
    {
        if (value is Enum)
        {
            return (Orientation)value;
        }
        return Orientation.Horizontal;
    }
    internal static Visibility CastAsVisibility(object value)
    {
        if (value is Enum)
        {
            return (Visibility)value;
        }
        return Visibility.Visible;
    }
}

我的问题是,Visual Studio设计器的wtf错误吗?而且,是否有更好的方法可以将这些对象强制转换为对应的Enum,以使设计人员不适合自己?

My question is, wtf is wrong with the Visual Studio designer? And, is there a better way to cast these objects to their corresponding Enum in such a way that the designer doesn't throw a fit?

推荐答案

我认为这可能会发生,因为在某些时候,使用错误的参数调用了转换器.您可以按照以下步骤在设计器中调试转换器的调用:

I think it might happen because at some point, the converter is called with bad arguments. You can debug the call the converter in the designer by following these steps :

  • 启动Visual Studio的新实例
  • 附加到第一个VS实例(工具->附加到进程)
  • 打开转换器源文件
  • 在Convert方法中放置一个断点
  • 在第一个VS实例中重新加载WPF设计器

这样,您应该能够检查传递给转换器的参数

That way you should be able to examine the arguments passed to the converter

这篇关于WPF Converter强制转换导致Visual Studio设计器异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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