我是一名编程新手,目前正在开发一个C# Windows Forms应用程序。
问题如下: 我有一个带有不同对象和控件的表单,例如:选项卡页面、文本框、计时器等。 我还有一个用户控件表单,我将其加载到主表单的一个选项卡页面中。
我想在用户控件中编写代码,如何操作主表单元素的属性。
例如:当我在用户控件表单上单击按钮时,它会将主表单的timer.Enabled控件设置为true。
我是一名编程新手,目前正在开发一个C# Windows Forms应用程序。
问题如下: 我有一个带有不同对象和控件的表单,例如:选项卡页面、文本框、计时器等。 我还有一个用户控件表单,我将其加载到主表单的一个选项卡页面中。
我想在用户控件中编写代码,如何操作主表单元素的属性。
例如:当我在用户控件表单上单击按钮时,它会将主表单的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");
}
}
}
timer1.Modifiers
属性设置为 "internal" 并使用 Form1
的实例进行访问:form1.timer1.Enabled = true;
Form1
的实例,而不是类本身。例如:// INVALID
Form1.timer1.Enabled = true;
// VALID
var form1 = Form1.ActiveForm;
form1.timer1.Enabled = true;
但这不是一种很干净的方法,你最好使用NDJ的答案中描述的事件。
form1.Timer1.Enabled = true
应该可以工作。 - pascalheinForm1
实例。相反,如我所建议的,您可以使用Form1.ActiveForm
或将对当前打开窗口的引用传递给UserControl
的构造函数。 - pascalheinpublic Control MainForm {
get;
set;
}
userControl1.MainForm = this;
protected button_click(object sender, EventArgs e)
{
timerName = "timer1";
EnableTimer(timerName);
}
private void EnableTimer(timerName)
{
var timer = MainForm.Controls.FirstOrDefault(z => z.Name.ToLower().Equals(timerName.ToLower());
if (timer != null)
{
((Timer)timer).Enabled = true;
} else {
// Timer was not found
}
}
public partial class MyUserControl : UserControl
{
/// You can name the event anything you want.
public event EventHandler ButtonSelected;
/// This bubbles the button selected event up to the form.
private void Button1_Clicked(object sender, EventArgs e)
{
if (this.ButtonSelected != null)
{
// You could pass your own custom arguments back to the form here.
this.ButtonSelected(this, e)
}
}
}
MyUserControl ctrl = new MyUserControl();
ctrl.ButtonSelected += this.ButtonSelected_OnClick;
最后在表单代码中,您将有一个订阅事件的方法,如下面的代码所示,它将使计时器启用。
private void ButtonSelected_OnClick(object sender, EventArgs e)
{
this.Timer1.Enabled = true;
}
你需要放置以下代码:
(`userControl11.OnButtonClicked += userControl11_OnButtonClicked;`)
在Visual Studio中,有一个单独的文件。另一个文件名为'Form1.Designer.cs'
,可以在Solution Explorer
面板下找到。
Form1 >> Form1.cs >> Form1.Designer.cs
。
希望这可以帮助你!