设置 "DependencyProperty.UnsetValue;" 时绑定错误

Binding error when setting "DependencyProperty.UnsetValue;"

我的视图中有这个变量绑定:

<Image Source="{Binding Path=GrappleTypeVar, Source={StaticResource CustomerData}, Converter={StaticResource GrappleDataConverter}}" Width="40" Height="40"/>

然后,这个转换器:

public class GrappleDataConverter : IValueConverter
{
    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            int currentType = (int)value;

            if (Enum.IsDefined(typeof(GrappleType), currentType))
            {
                switch ((GrappleType)currentType)
                {
                    case GrappleType.Hydraulic:
                        return String.Empty;
                    case GrappleType.Parallel:
                        return "/GUI;component/Images/040/SensorSoft.png";
                }
            }
        }
        // Not defined... Set unknown image
        return String.Empty;
    }

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

使用该代码,我的结果 windows 返回了很多类型的绑定错误:

System.Windows.Data 信息:10:无法使用绑定检索值并且不存在有效的回退值;使用默认代替。 BindingExpression:Path=GrappleTypeVar; DataItem='CustomerData' (哈希码=50504364);目标元素是 'Image' (Name='');目标 属性 是 'Source'(类型 'ImageSource') System.Windows.Data 错误:23:对于具有默认转换的 'en-US' 文化,无法将 '' 从类型 'String' 转换为类型 'System.Windows.Media.ImageSource';考虑使用 Converter 属性 的 Binding。 NotSupportedException:'System.NotSupportedException: ImageSourceConverter 无法从 System.String.

转换

查看该错误,我找到了解决方案: ImageSourceConverter error for Source=null

我更改了我的代码:

case GrappleType.Hydraulic:
    return String.Empty;

对于

case GrappleType.Hydraulic:
    return DependencyProperty.UnsetValue;

现在应用程序运行更流畅了,但结果windows出现了以下绑定错误: System.Windows.Data 信息:10:无法使用绑定检索值并且不存在有效的回退值;使用默认代替。 BindingExpression:Path=GrappleTypeVar; DataItem='CustomerData' (哈希码=62171008);目标元素是 'Image' (Name='');目标 属性 是 'Source'(类型 'ImageSource')

谁能帮帮我?是否可以解决此错误?

谢谢!

您的转换器应该 return 一个与目标类型 属性 匹配的值,即从 ImageSource 派生的类型的实例。这通常是 BitmapImageBitmapFrame。如果不显示图像,则应 return null:

public object Convert(
    object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    object result = null;

    if (value is GrappleType)
    {
        switch ((GrappleType)value)
        {
            case GrappleType.Hydraulic:
                break;

            case GrappleType.Parallel:
                result = new BitmapImage(new Uri(
                    "pack://application:,,,/GUI;component/Images/040/SensorSoft.png"));
                break;
        }
    }

    return result;
}

请注意转换器如何使用 Resource File Pack URI 创建 BitmapImage。