2011-03-17 105 views
0

我正在創建一個應用程序,其中呈現的圖像的源在某些int值更改時發生更改。 要做到這一點,我想圖像的「來源」屬性綁定:將圖像的源代碼綁定到圖像資源

<Image Source="{Binding Path=Gas, Converter={StaticResource GasToImageSource}}"/> 

(天然氣是一個int值)。和轉換器:

public class GasToImageSource : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     int gas_value = (int)value; 
     if (gas_value <=500) 
      return SomeNameSpace.Properties.Resources.GAS_INDICATOR1; 
     if (gas_value <=1000) 
      return SomeNameSpace.Properties.Resources.GAS_INDICATOR2; 
     if (gas_value <= 1500) 
      return SomeNameSpace.Properties.Resources.GAS_INDICATOR3; 

     return SomeNameSpace.Properties.Resources.GAS_INDICATOR4; 
    } 

    ... 
} 

但由於某種原因,這是行不通的。 我的綁定有什麼問題?

回答

0

您需要提供ImageSource對象,而不是字符串。嘗試類似的東西:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    int gas_value = (int)value; 
    string res = SomeNameSpace.Properties.Resources.GAS_INDICATOR4; 
    if (gas_value <=500) 
     res = SomeNameSpace.Properties.Resources.GAS_INDICATOR1; 
    if (gas_value <=1000) 
     res = SomeNameSpace.Properties.Resources.GAS_INDICATOR2; 
    if (gas_value <= 1500) 
     res = SomeNameSpace.Properties.Resources.GAS_INDICATOR3; 

    BitmapImage img = new BitmapImage(); 
    img.BeginInit(); 
    img.UriSource = new Uri(res, UriKind.Relative); 
    img.EndInit(); 
    return img; 
} 
1

使用字符串就可以更改綁定到這一點:

Source="{Binding Path=Gas, StringFormat={}/your_namespace;component/{0}, Converter={StaticResource GasToImageSource}}"