【问题标题】:Changing a Image Source at runtime does not display the image在运行时更改图像源不会显示图像
【发布时间】:2011-08-23 09:10:36
【问题描述】:

我正在尝试根据其绑定值在 ListBox.ItemTemplate 中显示图像,绑定值是对象的状态(待处理、已检索、已发布、完成或错误),这是 Image 元素的 XAML .

<Window.Resources>
    <local:StatusImageConverter x:Key="StatusImage" />
</Window.Resources>

<Image Source="{Binding Path=Status, Converter={StaticResource StatusImage}}" />

我在 Project 资源中添加了 2 张图片(Badge_tick、Badge_cross)并使用 IValueConverter 接口将状态转换为将显示在模板中的图片,这里是 Converter 类

[ValueConversion(typeof(PreTripItem.PreTripItemStatus), typeof(Bitmap))]
public class StatusImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        PreTripItem.PreTripItemStatus status = (PreTripItem.PreTripItemStatus)value;

        switch (status)
        {
            case PreTripItem.PreTripItemStatus.Complete:
                return new Bitmap(Properties.Resources.Badge_tick);
            case PreTripItem.PreTripItemStatus.Error:
                return new Bitmap(Properties.Resources.Badge_cross);
            default:
                return null;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();  //Does not need to be converted back
    }
}

这可以很好地构建/编译并运行,但是当状态更改时,模板项中不会显示图像。我在我的类中使用 INotifyPropertyChanged 接口,所以接口知道属性何时自动更改,所以我马上知道这不是问题:)

我浏览了谷歌大学,看到很多帖子原则上存在相同的问题,但在使用转换器界面和项目资源时没有找到解决方案。

有人可以帮忙吗?提前致谢

我所有的其他 IValueConverter 类都运行良好,只是不是这个。

【问题讨论】:

    标签: wpf c#-4.0 binding ivalueconverter imagesource


    【解决方案1】:

    尝试返回一个 BitmapSource 类型来代替 Bitmap

    需要改变的地方:

    [ValueConversion(typeof(PreTripItem.PreTripItemStatus), typeof(BitmapSource))] 
    

    并返回一个 BitmapImage,如下所示:

    return new BitmapImage(new Uri("pack://application:,,,/Resources/Image1.png"));
    

    【讨论】:

    • 这已经成功了,谢谢。你回答的唯一缺点我现在必须学习 Uri 的大声笑
    【解决方案2】:

    我怀疑问题可能在于您使用标准 Bitmap 类,它不是 ImageSource 派生类型。

    您需要使用 ImageSource 类型: http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx

    如果您不了解包 URI,请查看此内容: http://msdn.microsoft.com/en-us/library/aa970069.aspx

    【讨论】:

    • 谢谢,关于 Pack Uri 的 MSN 文章很有帮助
    猜你喜欢
    • 2011-01-26
    • 1970-01-01
    • 2012-11-07
    • 2018-01-18
    • 2015-08-20
    • 2015-10-19
    • 2015-08-16
    相关资源
    最近更新 更多