IValueConverter无法与Designer一起使用

时间:2017-03-25 23:28:15

标签: c# wpf xaml ivalueconverter

拥有此IValueConverter可以在运行时完美地完成工作,但它似乎不适用于设计师

public class NameToUriConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (Enum.IsDefined(typeof(Enumerations.RelicTypes), value.ToString())) return new Uri("/Assets/RelicIcons/Relic_" + (value).ToString() + ".png", UriKind.Relative);

        else return new Uri("/Assets/Placeholder.png", UriKind.Relative);
    }

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

我使用它如下:

<Image Source="{Binding Type, Converter={StaticResource NameToUriConverter}}"/>

无论如何也可以在设计时完成这项工作吗?

编辑:我将调试器附加到VS进程,以便我可以在设计时调试IValueConverter。转换器返回此字符串

  

“/资产/ RelicIcons / Relic_Lith.png”

如果我直接在XAML代码中替换它

<Image Source="/Assets/RelicIcons/Relic_Lith.png"/>

一切都按预期工作。这让我觉得设计师处理Binding表达式的方式有问题。我不知道是否应该传回Uristring或其他内容。根据MSDN,source属性应设置为Uristring

编辑:调试Nkosi的答案这就是转换器的Locals的样子enter image description here我还打开了解决方案资源管理器来验证文件路径是否正确

1 个答案:

答案 0 :(得分:1)

尝试以下方法。它将URL转换为图像的图像源。在运行时,还有其他事情将URL转换为适当的图像控件源。

将您的转换器重构为此...

public class NameToUriConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        Uri source = value as Uri;
        var path = Enum.IsDefined(typeof(Enumerations.RelicTypes), value.ToString())) 
            ? string.Format("/Assets/RelicIcons/Relic_{0}.png", (value).ToString())
            : "/Assets/Placeholder.png";

        try {
            source = new Uri(path, UriKind.RelativeOrAbsolute);
        } catch {
            source = new Uri(path);
        }

        var img = new BitmapImage();
        img.BeginInit();
        img.UriSource = source;
        img.EndInit();

        return img;            
    }

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

此问题也可能与资源的路径相关联。在运行时,路径将被正确解析,但在设计时,图像的位置可能不会以相同的方式定位。在设计时查看图像的位置。要证明它在设计时手动设置控件上的路径并监视有效的路径。用类似的路径修改转换器,看它是否有效。