C#,绑定新的BitmapImage,WPF MVVM

3

我对WPF MVVM不熟悉,我在绑定新的BitmapImageImage.Source控件时遇到了问题。

从文件路径绑定图像很容易,但如何在WPF中将新的BitmapBitmapImage绑定到Image标签?

我的方案:

我有一个处理图像的方法(它隐藏在Model文件夹中的Class中):

static public BitmapImage Init(Bitmap bmp)
    {
        //Do stuff

        return BitmapConversion.Bitmap2BitmapImage(newImage); 

        //BitmapConversion is my own class for converting images
    }

在这个部分,我描述了我想要对我的位图进行的操作并返回BitmapImage
ViewModel中,我有以下内容:打开图像和初始化函数,我想要:
namespace Test.ViewModels
{
    class ViewModel
    {
        public string filepath { get; set; }

        public ViewModel()
        {

            OpenFileDialog openPicture = new OpenFileDialog();
            openPicture.Filter = "Image files|*.bmp;*.jpg;*.gif;*.png;*.tif|All files|*.*";
            openPicture.FilterIndex = 1;

            if (openPicture.ShowDialog() == true) 
            {
                filepath = openPicture.FileName;

                Model.Init(new Bitmap(filepath)); //init function from above
            }

        }

        public string DisplayedImage
        {
            get { return filepath; }
        }

    }

我的 View 长这样:

<!-- row1 -->
<Image Source="{Binding DisplayedImage}" />

<!-- row2 -->
<Image Source ={Binding ?}" />

我的问题是,如何正确地将像BitmapImage这样的对象绑定到Image标签的源?感谢任何建议。
1个回答

2
这将使用ImageSource而不是字符串来实现:
public ImageSource DisplayedImage
{
    get { return new BitmapImage(new Uri(filepath)); }
}

或者使用您的ViewModel:

class ViewModel
{
    public ViewModel()
    {
        ...

        if (openPicture.ShowDialog() == true) 
        {
            DisplayedImage = Model.Init(new Bitmap(openPicture.FileName));
        }
    }

    public ImageSource DisplayedImage { get; private set; }
}

然而,您应该考虑使用操作WPF BitmapSource的方法替换Model.Init方法,而不是WinForms Bitmap。


1
如果像你说的那么容易,我感觉有点傻呢:D - user9687180

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接