Dot-Net

Source=null 的 ImageSourceConverter 錯誤

  • March 23, 2011

我將 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)’

我寧願不顯示它,因為它只是噪音 - 有什麼方法可以抑制它?

@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)也可以消除異常,但仍然會影響性能(並且沒有必要)。

當然,您還需要管道:

在資源中:

&lt;local:NullImageConverter x:Key="nullImageConverter"/&gt;

你的形象:

&lt;Image Source="{Binding Path=ImagePath, Converter={StaticResource nullImageConverter}}"/&gt;

引用自:https://stackoverflow.com/questions/5399601