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

3

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

是否可以直接将 System.Drawing.Bitmap 对象绑定到 PictureBoxImage 属性?我尝试使用 PictureBox.DataBindings.Add(...),但似乎不起作用。

我应该怎么做呢?

谢谢并致以最良好的祝愿,
Oliver


如果您有一个位图,您可以在运行时将其分配给PictureBox的Image属性 - 请参阅http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.image.aspx - dash
你希望使用什么作为你的数据源? - Mark Hall
3个回答

4
这对我来说可行:
Bitmap bitmapFromFile = new Bitmap("C:\\temp\\test.bmp");

pictureBox1.Image = bitmapFromFile;

或者,用一行表述:
pictureBox1.Image = new Bitmap("C:\\temp\\test.bmp");

你可能过于复杂化了 - 根据MSDN文档,你可以直接将位图分配给PictureBox.Image属性。

谢谢你的回答。 事实上,我知道这个 :) ... 但是我认为使用数据绑定是“.Net方式”吧!? - Baldewin
@Baldewin - 这取决于您的数据模型;数据绑定对于实际数据非常常见,并且在您预期基础数据发生更改时非常有用 - 与此数据“绑定”的控件通常会自动刷新。您可以对图像框执行此操作,但是直接管理PictureBox.Image属性要简单得多;您还可以控制何时处理图像,这在某些情况下可能很重要。我以前使用过图像文件路径来完成此操作 - 因此,该DataBinding语法为pictureBox.DataBindings.Add("ImageLocation", dataTable, "FilePath"); - dash
@Baldewin 如果您让我知道您用于数据绑定的确切代码,我会尝试帮助您;请注意,这不是必须的,而直接设置Image属性(或ImageLocation属性)则更为常见。 - dash

3
你可以使用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;
}

我也使用了pictureBox.DataBindings.Add("Image", dataSource, dataMember, true); 最后一个参数很重要。 - Kirsten

2

您可以做:

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

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