结合图像属性WPF与资源图像 [英] Binding image to property in wpf with image from resources

查看:231
本文介绍了结合图像属性WPF与资源图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经包括了我的项目的一些图片。

i have some pictures included to my project.

这行code的正常工作:

this line of code works fine:

<Image Stretch="UniformToFill" Source="/Images/OffsetSituations/offsetsituation1.jpg"

但我要的图片从VM改变,所以我做了一个属性绑定到:

but i have to change the picture from the VM so i made a property to bind to:

private ImageSource _image;
public ImageSource Image
{
    get { return _image; }
    set
    {
        if (_image == value)
            return;
        _image = value;
        RaisePropertyChanged("Image");
    }
}

从这里计算器我得到这个code和改变了它一下另一篇文章:

from another post here on stackoverflow i got this code and changed it a bit:

string picture = "offsetsituation1";
if (!string.IsNullOrEmpty(picture))
{
    var image = new BitmapImage(new Uri(String.Format("/Images/OffsetSituations/{0}.jpg", picture), UriKind.Relative));
    image.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject"
    Image = image;
}
else
{
    Image = null;
}

现在在XAML:

<Image Stretch="UniformToFill" Source="{Binding Image}" Margin="5"/>

但绝不是一个图片。

but there never is a picture.

我加入 MessageBox.Show(Image.ToString()); 图像=图像; 调试。它显示了 /Images/OffsetSituations/offsetsituation1.jpg ,因此该路径似乎是正确的。

i added MessageBox.Show(Image.ToString()); after Image = image; to debug. it shows /Images/OffsetSituations/offsetsituation1.jpg, so the path seems to be right.

我在做什么错在这里?

推荐答案

WPF为大多数的框架类型,包括ImageSource的

WPF provide implicit converters for most of the framework types including ImageSource

所有您需要做的是提供正确的图像路径​​字符串,让隐性转换器做休息

all you have to do is provide the correct image path as string and let the implicit converter do the rest

所以更改图片属性的类型为字符串

so change the type of Image property to string

例如

public string Image
{
    get { return _image; }
    set
    {
        if (_image == value)
            return;
        _image = value;
        RaisePropertyChanged("Image");
    }
}

和指定的路径作为一个字符串

and assign the path as a string

Image = String.Format("/Images/OffsetSituations/{0}.jpg", picture);

这就是所有你需要来显示图像,其余部分将通过框架内加以处理。

that's all you need to show the image, rest will be handled by the framework

隐式转换器在许多地方,包括这一次如此得心应手。

implicit converter are so handy in many places including this one.

这篇关于结合图像属性WPF与资源图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆