【问题标题】:Binding image to property in wpf with image from resources使用来自资源的图像将图像绑定到 wpf 中的属性
【发布时间】:2014-09-18 13:22:25
【问题描述】:

我的项目中包含了一些图片。

这行代码运行良好:

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

但我必须从 VM 更改图片,所以我创建了一个属性来绑定:

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

从 stackoverflow 上的另一篇文章中,我得到了这段代码并对其进行了一些更改:

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"/>

但从来没有图片。

我在Image = image; 之后添加了MessageBox.Show(Image.ToString()); 以进行调试。它显示/Images/OffsetSituations/offsetsituation1.jpg,所以路径似乎是正确的。

我在这里做错了什么?

【问题讨论】:

  • 尝试使用public string Image 而不是public ImageSource Image,然后让隐式转换器完成剩下的工作。

标签: c# wpf image binding embedded-resource


【解决方案1】:

WPF 为包括 ImageSource 在内的大多数框架类型提供隐式转换器

您所要做的就是提供正确的图像路径作为字符串,然后让隐式转换器完成其余的工作

所以将Image属性的类型改为string

例如

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

并将路径分配为字符串

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

这就是显示图像所需的全部内容,其余的将由框架处理

隐式转换器在包括这个在内的许多地方都非常方便。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    相关资源
    最近更新 更多