为了账号安全,请及时绑定邮箱和手机立即绑定

如何从主窗体上的按钮调用 UserControl 中的函数 C#

如何从主窗体上的按钮调用 UserControl 中的函数 C#

C#
慕田峪7331174 2023-09-16 15:04:38
我有一个带有用户控件的主窗体,当按下用户控件上的面板时,会显示图像。我想在主窗体上创建一个按钮,当我按下它时,之前出现的图像再次隐藏(就像用户控件第一次初始化时一样)我在用户控件中创建了一个类(这是项目的一部分),并在其中创建了一个函数来隐藏图像(如果它们已经出现)。以下代码没有显示错误,但不起作用。请你帮助我好吗?public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();          }        private void button_reset_Click(object sender, EventArgs e)        {            UserControl_axi user_ax = new UserControl_axi();            UserControl_axi.Rst_userControl.Rst_Axi(user_ax);public class Rst_userControl         {            public static void Rst_Axi(UserControl_axi rst)            {                rst.pictureBox5.Hide();                rst.pictureBox6.Hide();           }        }
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

起初,我觉得有些事情很奇怪:为什么要在按钮操作中创建其他用户控件?它不是您在加载表单时可能看到的表单,因为它是在您的方法中创建的,然后在完成后删除。

您的表单中必须有另一个UserControl_axi变量/实例,并且这是您必须在Rst_Axi方法中用作参数的变量/实例


private void button_reset_Click(object sender, EventArgs e)

{

    // New user control user_ax ???? -> To be removed

    UserControl_axi user_ax = new UserControl_axi();

    // Changes applied to an "invisible" user_ax -> Argument to be replaced with the property of your Form of type UserControl_axi

    UserControl_axi.Rst_userControl.Rst_Axi(user_ax);

    // After this user_ax will be destroyed

}

此外,如果你的Rst_userControl类除了声明该方法之外没有其他用途,Rst_Axi我建议你放弃它并直接声明Rst_Axi()为UserControl_axi. 因为你这样做的方式太过分了:)


public partial class UserControl_axi

{

    // Not static anymore 

    public void Rst_Axi()

    {

         // No arguments because pictureBox5 and pictureBox6 are properties of the current usercontrol

         this.pictureBox5.Hide();

         this.pictureBox6.Hide();

    }

}

并打电话


private void button_reset_Click(object sender, EventArgs e)

{

     // Use the property in your form related to the UserControl_axi and call its reset method

     this.userControl_axio1.Rst_Axi();

}


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 70 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信