将Image的源绑定到图像资源

时间:2011-03-17 07:26:33

标签: wpf image

我正在构建一个应用程序,在该应用程序中,当一些int值发生变化时,我会呈现一个源会发生变化的图像。 为此,我试图绑定图像的'Source'属性:

<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;
    }

   ...
}

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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;
}