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

我是编程新手,现在正在使用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");
        }


        }
    }

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...