微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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


        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐