如何从另一个UserControl更改UserControl上的图片框

时间:2017-03-27 21:57:37

标签: c# winforms user-controls

On UserControl1我想让pictureBox1(在UC1上)与UserControl2上的pictureBox1相同。

在UC1上

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

在UC5上

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

这似乎不起作用。

修改

在UC1上

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

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

在UC5上

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

1 个答案:

答案 0 :(得分:0)

在UC5上添加一个事件,当图像被更改并且UC1订阅它时将触发该事件。

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;
}

每当UC5.Image更新时,这应该更新UC1上的图片框。