加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在表单之外到达和设置控件的属性?

发布时间:2020-12-16 01:54:07 所属栏目:百科 来源:网络整理
导读:我是编程新手,现在正在使用C# Windows Forms应用程序. 问题如下: 我有一个表单,其中包含不同的对象和控件,如:tabpages,textboxes,timers等. 我还有一个UserControl表单,我将其加载到Form的主要页面之一. 我想在UserControl中编写代码,如何操作主Form的元素
我是编程新手,现在正在使用C# Windows Forms应用程序.

问题如下:
我有一个表单,其中包含不同的对象和控件,如:tabpages,textboxes,timers等.
我还有一个UserControl表单,我将其加载到Form的主要页面之一.

我想在UserControl中编写代码,如何操作主Form的元素属性.

例如:当我单击UserControl表单上的按钮时,它将主Form的timer.Enabled控件设置为true.

解决方法

可以这样做,但让用户控制访问和操作表单不是最干净的方式 – 让用户控件引发事件并让托管表单处理事件会更好. (例如,在处理按钮单击时,表单可以启用/禁用计时器等)

这样,如果需要,您可以以不同的方式使用用户控件来处理不同的表单;它使得发生的事情变得更加明显.

更新:
在您的用户控件中,您可以声明一个事件 – 在按钮单击中,您引发事件:

namespace WindowsFormsApplication1
{
    public partial class UserControl1 : UserControl
    {
        public event EventHandler OnButtonClicked;


        public UserControl1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender,EventArgs e)
        {
            EventHandler handler = OnButtonClicked;

            // if something is listening for this event,let let them know it has occurred
            if (handler != null)
            {
                handler(this,new EventArgs());
            }

        }
    }
}

然后在表单中添加用户控件.然后你可以挂钩事件:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            userControl11.OnButtonClicked += userControl11_OnButtonClicked;
        }

        void userControl11_OnButtonClicked(object sender,EventArgs e)
        {
            MessageBox.Show("got here");
        }


        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读