55

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

System.Windows.Data 错误:23:无法使用默认转换将“<null>”从类型“<null>”转换为“en-AU”文化类型的“System.Windows.Media.ImageSource”;考虑使用 Binding 的 Converter 属性。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)'

我宁愿不显示它,因为它只是噪音 - 有什么方法可以抑制它?

4

3 回答 3

100

@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();
    }
}

ReturningDependencyProperty.UnsetValue还解决了抛出(和忽略)所有这些异常的性能问题。返回 anew BitmapSource(uri)也可以消除异常,但仍然会影响性能(并且没有必要)。

当然,您还需要管道:

在资源中:

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

你的形象:

<Image Source="{Binding Path=ImagePath, Converter={StaticResource nullImageConverter}}"/>
于 2011-04-11T22:34:44.760 回答
11

我使用了 Pat 的 ValueConverter 技术,效果很好。我还尝试了来自此处的 flobodob 的 TargetNullValue 技术,它也很有效。它更容易,更清洁。

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

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

于 2018-11-27T18:51:10.437 回答
6

将图像直接绑定到对象上,并在必要时返回“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");
        }
    }
于 2013-09-10T09:30:13.887 回答