【问题标题】:Binding the source of an Image to image resources将图像的来源绑定到图像资源
【发布时间】:2011-03-17 07:26:33
【问题描述】:

我正在构建一个应用程序,在该应用程序中,我展示了一个图像,当某个 int 值发生变化时,该图像的源会发生变化。 为此,我正在尝试绑定图像的“源”属性:

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

(Gas 是一个 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;
    }

   ...
}

但由于某种原因,这不起作用。 我的绑定有什么问题?

【问题讨论】:

    标签: wpf image


    【解决方案1】:

    要使用字符串,您可以将绑定更改为:

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

    【讨论】:

      【解决方案2】:

      您需要提供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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        相关资源
        最近更新 更多