Windows窗体:如何直接绑定一个位图到一个图片? [英] Windows Forms: How to directly bind a Bitmap to a PictureBox?

查看:93
本文介绍了Windows窗体:如何直接绑定一个位图到一个图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想建立一个小型的C#.net 4.0应用程序中使用Windows窗体(WPF我不知道在所有的Windows窗体至少有一点:-))。

I'm just trying to build a small C# .Net 4.0 application using Windows Forms (WPF I don't know at all, Windows Forms at least a little :-) ).

是否有可能直接绑定 System.Drawing.Bitmap 对象的图片的属性图片框?我试图用 PictureBox.DataBindings.Add(...),但是这似乎并没有工作。

Is it possible to directly bind a System.Drawing.Bitmap object to the Image property of a PictureBox? I tried to use PictureBox.DataBindings.Add(...) but this doesn't seem to work.

我怎样才能做到这一点?

How can I do this?

感谢和问候,
奥利弗

Thanks and best regards,
Oliver

推荐答案

您可以使用PictureBox.DataBindings.Add(...)
关键是要创建要绑定到处理空和空画面之间的转换在对象上一个单独的属性。

You can use the PictureBox.DataBindings.Add(...)
The trick is to create a separate property on the object you are binding to to handle the conversion between null and and empty picture.

我就是这么做的。

在我的窗体加载我用

this.PictureBox.DataBindings.Add(new Binding("Visible", this.bindingSource1, "HasPhoto", false, DataSourceUpdateMode.OnPropertyChanged));

this.PictureBox.DataBindings.Add(new Binding("Image", this.bindingSource1, "MyPhoto",false, DataSourceUpdateMode.OnPropertyChanged));

在我的对象,我有以下

[NotMapped]
    public System.Drawing.Image MyPhoto
    {
        get
        {

            if (Photo == null)
            {
                return BlankImage;   

            }
            else
            {
                if (Photo.Length == 0)
                {
                    return BlankImage;  

                }
                else
                {
                    return byteArrayToImage(Photo);
                }
            }

        }
        set
        {
            if (value == null)
            {
                Photo = null;
            }
            else
            {


                if (value.Height == BlankImage.Height)  // cheating
                {
                    Photo = null;
                }
                else
                {
                    Photo = imageToByteArray(value);
                }
            }

        }
    }

    [NotMapped]
    public Image BlankImage {
        get
        {

            return new Bitmap(1,1);
        }
    }

    public static byte[] imageToByteArray(Image imageIn)
    {

            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, ImageFormat.Gif);
            return ms.ToArray();

    }

    public static Image byteArrayToImage(byte[] byteArrayIn)
    {

            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;

    }

这篇关于Windows窗体:如何直接绑定一个位图到一个图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆