2016-02-10 76 views
0

我必須在我看來這個變量綁定:設置「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(); 
    } 
} 

使用的代碼,我的結果窗口返回了很多類型的綁定錯誤的:

System.Windows.Data信息:10:無法使用綁定檢索值並且不存在有效的回退值;改爲使用默認值。 BindingExpression:路徑= GrappleTypeVar; DataItem ='CustomerData'(HashCode = 50504364);目標元素是'Image'(Name ='');目標屬性是'Source'(類型'ImageSource') System.Windows.Data錯誤:23:無法將類型'String'轉換爲類型'System.Windows.Media.ImageSource'for'en-US'culture with默認轉換;考慮使用Binding的Converter屬性。 NotSupportedException:'System.NotSupportedException:ImageSourceConverter無法從System.String轉換。

審查的錯誤,我發現的解決方案: ImageSourceConverter error for Source=null

而且我在我的代碼更改:

case GrappleType.Hydraulic: 
    return String.Empty; 

case GrappleType.Hydraulic: 
    return DependencyProperty.UnsetValue; 

現在,應用程序運行更流暢,但在結果窗口中出現以下綁定錯誤: System.Windows.Data信息:10:無法檢索ve值使用綁定並且不存在有效的回退值;改爲使用默認值。 BindingExpression:路徑= GrappleTypeVar; DataItem ='CustomerData'(HashCode = 62171008);目標元素是'Image'(Name ='');目標屬性是'源'(類型'ImageSource')

任何人都可以提供一些幫助嗎?有沒有可能解決這個錯誤?

謝謝!

+1

'Image.Source'是一個抽象類型'ImageSource'(不能被實例化)。在你的轉換器中,你應該返回一個派生類對象,比如'BitmapImage',而不是一個字符串。 – Peter

回答

1

您的轉換器應返回與目標屬性類型相匹配的值,即從ImageSource派生的類型實例。這通常是BitmapImageBitmapFrame。在情況下,應沒有圖像顯示,它應該返回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。

相關問題