2

Windowsフォームを使用して小さなC#.Net 4.0アプリケーションを構築しようとしています(WPFはまったく知りませんが、Windowsフォームは少なくとも少し:-))。

System.Drawing.Bitmapオブジェクトを のImageプロパティに直接バインドすることは可能PictureBoxですか? 使ってみましPictureBox.DataBindings.Add(...)たが、うまくいかないようです。

これどうやってするの?

よろしくお願いします、
オリバー

4

3 に答える 3

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;
}
于 2014-06-05T04:43:13.443 に答える
3

これは私のために働く:

Bitmap bitmapFromFile = new Bitmap("C:\\temp\\test.bmp");

pictureBox1.Image = bitmapFromFile;

または、1行で:

pictureBox1.Image = new Bitmap("C:\\temp\\test.bmp");

これを複雑にしすぎている可能性があります-MSDNのドキュメントによると、ビットマップをPictureBox.Imageプロパティに直接割り当てるだけです。

于 2012-07-01T15:33:16.457 に答える
1

できるよ:

System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourfile.bmp");
picturebox1.Image = bmp;
于 2012-07-01T15:34:02.157 に答える