简体   繁体   English

图片框的可见属性无法在C#中使用其他表单

[英]Visible Property of Picture box not working from another form in C#

Hi I am using windows forms in C#. 嗨,我在C#中使用Windows窗体。 I am trying to modify the visible property of a picture from main form to another. 我试图将图片的可见属性从主窗体修改为另一个。 Initially, the visible property of the picture box is set to false. 最初,图片框的visible属性设置为false。 On a button click from another form, the visible property of the picture box is modified to true. 在从另一个表单单击按钮时,图片框的visible属性将修改为true。

This is the code written in the Form2 method: 这是用Form2方法编写的代码:

private void button_Click(object sender, EventArgs e)
{
    public Form1 frm1 = new Form1();
    frm1.pictureBox.Visible= true;
}

Form1 is an instance type, so when you do Form1是一个实例类型,所以当你这样做

public Form1 frm1 = new Form1();
frm1.pictureBox.Visible= true;

you're really just creating a new instance of Form1 completely unrelated from your original Form1 , changing a picture-box's visible property on it, and then discarding it. 你真的只是创造的一个新实例Form1从原来的完全不相关的Form1 ,就可以改变一个图片框的Visible属性,然后将其丢弃。


What you can do, is put a reference to the "parent" Form1 inside your Form2 class. 您可以做的是,在Form2类中引用“父” Form1

Here's an example 这是一个例子

public partial class Form2 : Form
{
    public Form2(Form1 parent)
    {
        InitializeComponent();
        this.Parent = parent;
    }

    Form1 Parent;

    private void button1_Click(object sender, EventArgs e)
    {
        Parent.pictureBox.Visible= true;
    }
    ...
}

there you create an instance of a form : 在那里你创建一个表单的实例:

public Form1 frm1 = new Form1();

This is then obviously NOT the form you already may have in your page, which you could simply access by its ID. 这显然不是您在页面中可能拥有的表单,您只需通过其ID访问即可。

According to your written code it will create new instance of the desired form, and NOT take the existing open form. 根据您编写的代码,它将创建所需表单的新实例,而不是采用现有的开放表单。 Hence to identify the existing open form containing target picture box you need the target form and controlling form be related by like Parent form or MDI Parent Form. 因此,要识别包含目标图片框的现有开放表单,您需要通过父表单或MDI父表单来关联目标表单和控制表单。 Assuming case of MDI Parent Form (ie Controlling form is MDI Parent of Target Form), you need following codes to identify to existing open form: 假设MDI父表格的情况(即控制表格是目标表格的MDI父母),您需要以下代码来识别现有的开放表格:

foreach (Form frm in MdiChildren)
        {
            if (frm is myTargetForm)
            {
                //do your code to find control using id of picture box and change the required properties
            }

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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