Windows窗体:如何直接将位图绑定到PictureBox?
我只是想尝试使用Windows Forms构建一个小型的C#.Net 4.0应用程序(WPF我根本不知道,Windows Forms至少有一点:-))。
是否可以直接将System.Drawing.Bitmap
对象绑定到PictureBox
的Image
属性? 我试图使用PictureBox.DataBindings.Add(...)
但这似乎不起作用。
我怎样才能做到这一点?
谢谢和最好的问候,
奥利弗
这对我有用:
Bitmap bitmapFromFile = new Bitmap("C:\\temp\\test.bmp"); pictureBox1.Image = bitmapFromFile;
或者,在一行中:
pictureBox1.Image = new Bitmap("C:\\temp\\test.bmp");
您可能会过度复杂 – 根据MSDN文档 ,您可以简单地将位图直接分配给PictureBox.Image属性。
你可以使用PictureBox.DataBindings.Add(…)
诀窍是在要绑定的对象上创建一个单独的属性来处理null和空图片之间的转换。
我是这样做的。
在我使用的表单加载中
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; }
你可以做:
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourfile.bmp"); picturebox1.Image = bmp;