Source = null的ImageSourceConverter错误

时间:2011-03-23 00:39:58

标签: .net wpf image exception-handling ivalueconverter

我将Image的Source属性绑定到字符串。此字符串可能为null,在这种情况下,我只是不想显示图像。但是,我在调试输出中得到以下内容:

  

System.Windows.Data错误:23:不能   转换'< null>'来自类型'< null>'至   类型   'System.Windows.Media.ImageSource'for   'en-AU'文化默认   转换;考虑使用Converter   Binding的财产。   NotSupportedException异常:的“System.NotSupportedException:   ImageSourceConverter无法转换   来自(null)。在   System.ComponentModel.TypeConverter.GetConvertFromException(对象   价值)   System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext   上下文,CultureInfo文化,对象   价值)   MS.Internal.Data.DefaultValueConverter.ConvertHelper(对象   o,输入destinationType,   DependencyObject targetElement,   CultureInfo文化,布尔   isForward)'

我更喜欢这个没有显示,因为它只是噪音 - 是否有任何方法可以抑制它?

3 个答案:

答案 0 :(得分:86)

@AresAvatar建议您使用ValueConverter是正确的,但该实现对此情况没有帮助。这样做:

public class NullImageConverter :IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return DependencyProperty.UnsetValue;
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // According to https://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convertback(v=vs.110).aspx#Anchor_1
        // (kudos Scott Chamberlain), if you do not support a conversion 
        // back you should return a Binding.DoNothing or a 
        // DependencyProperty.UnsetValue
        return Binding.DoNothing;
        // Original code:
        // throw new NotImplementedException();
    }
}

返回DependencyProperty.UnsetValue还解决了抛出(并忽略)所有这些异常的性能问题。返回new BitmapSource(uri)也可以摆脱异常,但仍有性能损失(并且没有必要)。

当然,你还需要管道:

资源:

<local:NullImageConverter x:Key="nullImageConverter"/>

你的形象:

<Image Source="{Binding Path=ImagePath, Converter={StaticResource nullImageConverter}}"/>

答案 1 :(得分:4)

将图像直接绑定在对象上,并在必要时返回“UnsetValue”

<Image x:Name="Logo" Source="{Binding ImagePath}"  />

ViewModel中的属性:

    private string _imagePath = string.Empty;
    public object ImagePath 
    {
        get
        {
            if (string.IsNullOrEmpty(_imagePath))
                return DependencyProperty.UnsetValue;

            return _imagePath;
        }
        set
        {
            if (!(value is string)) 
                return;

            _imagePath = value.ToString();
            OnPropertyChanged("ImagePath");
        }
    }

答案 2 :(得分:1)

我使用了Pat的ValueConverter技术,效果很好。 我还尝试了here的flobodob的TargetNullValue技术,它也很好用。

<Image Source="{Binding LogoPath, TargetNullValue={x:Null}}" />

TargetNullValue更简单,并且不需要转换器。