我正在创建 Windows 窗体应用程序,它的主窗体包含一个面板。单击按钮时会在该面板上加载不同的用户控件。
namespace LearnCSharp
{
public partial class MainForm : Form
{
private void configButton_Click(object sender, EventArgs e)
{
var uControllerDashboard = new Controllers.Dashboard();
panel.Controls.Add(uControllerDashboard);
updateNotification("active");
}
private void updateNotification(string state)
{
switch (state)
{
case "active" :
//Do something here
break;
}
}
}
}
当点击配置按钮时,它会将仪表板用户 Controller 加载到面板中,在仪表板用户控件中还有另一个应用按钮。当我单击该按钮时,我需要调用 MainForm 类 中的 updatNotification 方法。
namespace LearnCSharp.Controllers
{
public partial class Dashboard : UserControl
{
private void btnApply_Click(object sender, EventArgs e)
{
// Need to call updateNotification method here.
}
}
}
我怎样才能达到我的要求。我感谢任何帮助。谢谢。
最佳答案
为此使用事件。
不是在 UserControl 中调用 MainForm,而是在 UserControl 中创建一个事件并让 MainForm 订阅该事件。在 UserControl 中,您只需触发事件。
网络上有很多这方面的例子。看看这个:
How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?
How do i raise an event in a usercontrol and catch it in mainpage?
希望这对您有所帮助。
关于c# - 如何从不同的类调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551170/