Windowsフォームを使用して小さなC#.Net 4.0アプリケーションを構築しようとしています(WPFはまったく知りませんが、Windowsフォームは少なくとも少し:-))。
System.Drawing.Bitmapオブジェクトを のImageプロパティに直接バインドすることは可能PictureBoxですか? 使ってみましPictureBox.DataBindings.Add(...)たが、うまくいかないようです。
これどうやってするの?
よろしくお願いします、
オリバー
Windowsフォームを使用して小さなC#.Net 4.0アプリケーションを構築しようとしています(WPFはまったく知りませんが、Windowsフォームは少なくとも少し:-))。
System.Drawing.Bitmapオブジェクトを のImageプロパティに直接バインドすることは可能PictureBoxですか? 使ってみましPictureBox.DataBindings.Add(...)たが、うまくいかないようです。
これどうやってするの?
よろしくお願いします、
オリバー
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;
}
これは私のために働く:
Bitmap bitmapFromFile = new Bitmap("C:\\temp\\test.bmp");
pictureBox1.Image = bitmapFromFile;
または、1行で:
pictureBox1.Image = new Bitmap("C:\\temp\\test.bmp");
これを複雑にしすぎている可能性があります-MSDNのドキュメントによると、ビットマップをPictureBox.Imageプロパティに直接割り当てるだけです。
できるよ:
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourfile.bmp");
picturebox1.Image = bmp;