Csharp/C#教程:Windows窗体:如何直接将位图绑定到PictureBox?分享


Windows窗体:如何直接将位图绑定到PictureBox?

我只是想尝试使用Windows Forms构建一个小型的C#.Net 4.0应用程序(WPF我根本不知道,Windows Forms至少有一点:-))。

是否可以直接将System.Drawing.Bitmap对象绑定到PictureBoxImage属性? 我试图使用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; } 

你可以做:

上述就是C#学习教程:Windows窗体:如何直接将位图绑定到PictureBox?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourfile.bmp"); picturebox1.Image = bmp; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1009530.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐