IValueConverter 不适用于 Designer

IValueConverter not working with Designer

这个 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。转换器returns 这个字符串

"/Assets/RelicIcons/Relic_Lith.png"

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

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

一切正常。这让我觉得设计者处理 Binding 表达式的方式有问题。我不知道我是否应该传回 Uristring 或其他内容。根据 MSDN,源 属性 应设置为 Uristring

编辑:调试 Nkosi 的答案这是转换器局部变量的样子我还打开了解决方案资源管理器以验证文件路径是否正确

尝试以下操作。它将 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();
    }
}

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