我真的是编程新手,目前正在开发 C# Windows 窗体应用程序。
问题如下: 我有一个包含不同对象和控件的表单,例如:标签页、文本框、计时器等。 我还有一个 UserControl 表单,我将其加载到主表单的一个标签页中。
我想在 UserControl 中编写代码,如何操作主窗体的元素属性。
例如:当我单击 UserControl 窗体上的按钮时,它会将主窗体的 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");
}
}
}
关于c# - 如何在窗体之外访问和设置控件的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15815299/