c# - 如何从不同的类调用类方法

标签 c# windows user-controls

我正在创建 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 中,您只需触发事件。

网络上有很多这方面的例子。看看这个:

希望这对您有所帮助。

关于c# - 如何从不同的类调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551170/

相关文章:

c# - 水平 ListView Xamarin.Forms

c# - 在 C#.net 运行时创建按钮?

c# - 如何使用 ExcelLibrary 更改 Excel 文件中的单元格样式?

python - celery :消费者:无法连接到 amqp://guest:**@127.0.0.1:5672//:[Errno 92] 协议(protocol)不可用

c++ - 我没有看到注册表项,即使 GetLastError 返回全 0

c# - 从自动回传中的下拉列表动态加载特定的用户控件

c# - 我如何告诉 Resharper 以不同方式设置这些字段属性的格式?

windows - 在Windows上的Meson Build中链接现有 `.lib`文件

c# - 对 ASP.Net 中 GridView 中的 TextBox 进行 JavaScript 验证

c# - 如何隐藏 ColumnDefinition 的内容