简体   繁体   中英

How to keep a reference of PictureBox Image attached to a variable and not to an object of the variable?

I work in C# and want to keep a reference of PictureBox.Image attached to a variable and not to an object of the variable. That means I want freely change the objects of this variable and PictureBox will always refers to the variable.

I have a class that manipulates images, merges them and returns image ImageShow to visualize in PictureBox. Often I have to assign new Image object to a variable. When I do so, PictureBox keeps the old object, while I want it to take a new one.

class Foo
{
   Image ImageShow = null;

   public void FooFunc()
   {
      //some code
      changeImageSize(new Size(600,800))
   }

   private void changeImageSize(Size newSize)
   {
      if(ImageShow != null)
         ImageShow.Dispose();
      ImageShow = new Bitmap(newSize.Width, newSize.Height);
   }
}

When I do a code like this:

var obj = Foo();
obj.SetImage(new Bitmap(50,50));
pictureBox.Image = obj.GetImage();
obj.FooFunc();

PictureBox keeps the destroyed old Image object. So I get an error if I try to do anything with PictureBox.

Returning a new image object every time creates to many dependencies between internal code of the class and PictureBox. So it is not the best solution for me.

Simple example:

Image img;

img = new Bitmap(200, 200);
pictureBox1.Image = img;

img = new Bitmap(300, 300);

Picturebox continues to refer to the old image

pictureBox1.Image.Size = {Width = 200 Height = 200}

While I want in to refers to the img variable and new object

You can either look into Binding the Image property of the PictureBox using PictureBox.Bindings.Add() and making an object to bind to that implements INotifyPropertyChanged so that when you set the image property for that object the Picturebox updates - or, much more simply, you can encapsulate ImageShow in a property and add the logic to update the picturebox to the setter.

private Image _imageShow = null;
public Image ImageShow {
    get {
        return _imageShow
    }
    set {
        _imageShow = value;
        pictureBox1.Image = value;
    }
}

Then, whenever you set ImageShow to a new image, the PictureBox will be set to the same image.

The reason your code doesn't work as-is is because ImageShow is storing a reference to the Image , and setting pictureBox1.Image sets the property to a reference to the same Image - but if you change what ImageShow is referencing the PictureBox will never see that, as it is referencing the original image, not the field ImageShow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM