如何将图像加载到 wpf 中的图像控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19782283/
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
How to load a image to image control in wpf?
提问by SNS
I'm developing an application in wpf with mvvm pattern.
我正在使用 mvvm 模式在 wpf 中开发应用程序。
in my application, i need to select a image and show in a form and then save it to database.
在我的应用程序中,我需要选择一个图像并以表格形式显示,然后将其保存到数据库中。
in the wpf form, i'm using a image control to display the image.
在 wpf 形式中,我使用图像控件来显示图像。
in my view model, I open the file dialog and assign the Image Property.
在我的视图模型中,我打开文件对话框并分配图像属性。
BitmapImage image;
public BitmapImage Image
{
get { return image; }
set
{
image = value;
RaisePropertyChanged("Image");
}
}
...
OpenFileDialog file = new OpenFileDialog();
Nullable<bool> result =file.ShowDialog();
if (File.Exists(file.FileName))
{
image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(file.FileName, UriKind.Absolute);
image.EndInit();
}
my xaml part is
我的 xaml 部分是
<Image Height="144" HorizontalAlignment="Left" Source="{Binding Image}"
Margin="118,144,0,0" Name="imgData" Stretch="Fill" VerticalAlignment="Top" Width="340" />
I'm not able to see the image in the form. How?
我无法在表单中看到图像。如何?
回答by Clemens
You have to assign the Imageproperty, not the imagefield. Otherwise the PropertyChanged event isn't raised:
您必须分配Image属性,而不是image字段。否则不会引发 PropertyChanged 事件:
if (File.Exists(file.FileName))
{
Image = new BitmapImage(new Uri(file.FileName, UriKind.Absolute));
}
Please note also that it would make sense to declare the Imageproperty to be of type ImageSource, which is a base class of BitmapImage. That would allow instances of other types derived from ImageSourceto be assigned to the property, e.g. BitmapFrameor WriteableBitmap.
另请注意,将Image属性声明为类型ImageSource是有意义的,它是 的基类BitmapImage。这将允许将派生自的其他类型的实例ImageSource分配给属性,例如BitmapFrame或WriteableBitmap。

