简体   繁体   中英

How to change picturebox on UserControl from another UserControl

On UserControl1 I want to make pictureBox1 (on UC1) to be the same as the pictureBox1 on UserControl2.

On UC1

UserControl5 obj = new UserControl5();
pictureBox1.Image = obj.picturebox;

On UC5

public Image picturebox
{
    get { return pictureBox1.Image; }
}

This seems to not be working.

EDIT


On UC1

public UserControl5 UserControl5Instance { get; set; }
public UserControl1()
{

    InitializeComponent();
    if (UserControl5Instance != null)
    {
        UserControl5Instance.picturebox = (Image)this.pictureBox1.Image.Clone();
    }
}

On UC5

public UserControl1 UserControl1Instance { get; set; }
public UserControl5()
{
    InitializeComponent();
}
public Image picturebox
{
    get { return this.pictureBox1.Image; }
    set { this.pictureBox1.Image = value; }
}

Add an event on UC5 that fires when the image is changed and have UC1 subscribe to it.

public class UC1 : UserControl
{
    UC5 UserControl5 = new UC5();
    PictureBox picturebox;

    public UC1()
    {
        picturebox = new PictureBox();
        UserControl5.ImageChanged += UserControl5_ImageChanged;
    }

    private void UserControl5_ImageChanged(Image newImage)
    {
        if (this.picturebox.Image != null)
            this.picturebox.Image.Dispose();
        this.picturebox.Image = (Image)newImage.Clone();
    }
}

public class UC5 : UserControl
{
    public delegate void ImageChangedHandler(Image newImage);

    public Image image {
        get { return _image; }
        set {
            if (_image != value) {
                _image = value;
                ImageChanged?.Invoke(_image);
            } } }
    public Image _image = null;
    public event ImageChangedHandler ImageChanged;
}

This should update the picturebox Image on UC1 whenever UC5.Image is updated.

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