【问题标题】:How to load a image to image control in wpf?如何将图像加载到 wpf 中的图像控件?
【发布时间】:2013-11-15 22:20:51
【问题描述】:

我正在使用 mvvm 模式在 wpf 中开发应用程序。

在我的应用程序中,我需要选择一张图片并以表格形式显示,然后将其保存到数据库中。

在 wpf 表单中,我使用图像控件来显示图像。

在我的视图模型中,我打开文件对话框并分配图像属性。

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();
}

我的 xaml 部分是

 <Image Height="144" HorizontalAlignment="Left" Source="{Binding Image}"
        Margin="118,144,0,0" Name="imgData" Stretch="Fill" VerticalAlignment="Top" Width="340" />

我无法在表单中看到图像。怎么样?

【问题讨论】:

标签: wpf image mvvm


【解决方案1】:

您必须分配 Image 属性,而不是 image 字段。否则不会引发 PropertyChanged 事件:

if (File.Exists(file.FileName))
{
    Image = new BitmapImage(new Uri(file.FileName, UriKind.Absolute));
}

还请注意,将Image 属性声明为ImageSource 类型是有意义的,它是BitmapImage 的基类。这将允许从ImageSource 派生的其他类型的实例分配给属性,例如BitmapFrameWriteableBitmap

【讨论】:

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