wpf 通过wpf中的属性绑定图片源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14358553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding image source through property in wpf
提问by Virus
I am trying to display an icon using an image source(.jpg). I create a Icon property in view model and try to assign it the path of the image but I do not see any image in the view. I tried converting the path to Bitmap image but doesn't work. Is there anything I am missing here?
我正在尝试使用图像源(.jpg)显示图标。我在视图模型中创建了一个 Icon 属性并尝试为它分配图像的路径,但我在视图中看不到任何图像。我尝试将路径转换为位图图像,但不起作用。有什么我在这里想念的吗?
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}"/>
<Image Source="{Binding Path=Icon}"></Image>
</StackPanel>
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource = new Uri("C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg", UriKind.Absolute);
img.EndInit();
Icon = img;
回答by Deruijter
I ran into this myself once and, though maybe not the best solution, the following worked for me.
我自己遇到过一次,虽然可能不是最好的解决方案,但以下对我有用。
1. Add the images to your project, for example:
1. 将图像添加到您的项目中,例如:
- Create a folder images/icons to your project and add the images there.
- Set build action of images to Content (copy if newer)
- 为您的项目创建一个文件夹图像/图标并在那里添加图像。
- 将图像的构建操作设置为内容(如果更新则复制)
2. Create an ImageSource property:
2. 创建一个 ImageSource 属性:
public ImageSource YourImage
{
get { return _yourImage; }
set
{
_yourImage = value;
NotifyOfPropertyChange(() => YourImage);
}
}
(Note: I use caliburn micro to assist in binding)
(注:本人使用caliburn micro协助装订)
3. Update the the ImageSource like this:
3. 像这样更新 ImageSource:
if(!string.IsNullOrEmpty("TheImageYouWantToShow"))
{
var yourImage = new BitmapImage(new Uri(String.Format("Images/Icons/{0}.jpg", TheImageYouWantToShow), UriKind.Relative));
yourImage.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject"
YourImage = yourImage;
}
else
{
YourImage = null;
}
4. Bind source attribute to YourImage property:
4. 将 source 属性绑定到 YourImage 属性:
(you already did this)
(你已经这样做了)