WPF Converter casting causes Visual Studio designer exception

Eri*_*ang 5 c# wpf visual-studio-2008 visual-studio

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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?

Tho*_*que 18

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

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

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

  • 在设计器中调试转换器的精彩提示+1 (2认同)
  • 设计者正在发送DependencyProperty.UnsetValue.感谢有关调试设计器的提示. (2认同)