【发布时间】: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