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