【问题标题】:Call a public MainWindow function from within a Page in WPF从 WPF 的页面中调用公共 MainWindow 函数
【发布时间】:2014-01-06 19:49:27
【问题描述】:

我有一个 WPF 应用程序,它有一个主窗口和几个页面,我可以像这样导航到:

例如从一页到另一页我使用:

NavigationService.Navigate(new MyPage1());

并从我的主窗口显示我使用的页面:

_mainFrame.Navigate(new PageHome());

我的 MainWindow 上有一个公共函数,我想从页面内调用它。

我该怎么做??

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您不应该直接调用该方法。

    您应该做的是在您的页面中引发一个事件并让 MainWindow 订阅该事件。然后,该事件处理程序可以调用相关方法。

    在PageHome中:

    public event EventHandler SomethingHappened;
    private void MakeSomethingHappen(EventArgs e){
        if(SomethingHappened != null){
            SomethingHappened(this, e);
        }
    }
    

    在主窗口中:

    pageHome.SomethingHappened += new EventHandler(pageHome_SomethingHappened);
    
    void pageHome_SomethingHappened(object sender, EventArgs e){
         MyMethod();
    }
    

    【讨论】:

    • 谢谢。我已经这样做了,但出现以下错误:非静态字段、方法或属性“PageHome.SomethingHappened”需要对象引用
    • 我将事件设为静态,它解决了问题,这样可以吗?
    • 我所做的一切都与此处描述的相同,但我仍然无法从MainWindow 触发我的pageHome_SomethingHappened 方法。我认为它与SomethingHappened 有一些事情要做(它可能保持null,未初始化),因为我知道MakeSomethingHappen 方法被调用。
    • 我只是想通为什么它不起作用:我忘记将页面设置到框架中,像这样:_mainFrame.Navigate(new PageHome());
    【解决方案2】:

    以下解决方案对我来说可以从另一个页面调用 MainWindow 函数;

    ((MainWindow)System.Windows.Application.Current.MainWindow).FunctionName(params);
    

    【讨论】:

      【解决方案3】:

      还有一种使用 Registry 的技术,这将是从另一个类调用一个类的函数的完美方式(在多个项目中拆分的类需要)。

      1. 使公共函数成为接口的一部分

        interface ISomeInterface { void RequierdMethod();}
        public partial class RequiedImplementer: Window, ISomeInterface 
        {
            void RequiredMethod() { }
        }
        
      2. Registry.RegisterInstance<ISomeInterface >(new RequiedImplementer()); //Initialize all interfaces and their corresponding in a common class.

      3. 在您的应用程序中的任何位置调用 apt 函数,如下所示

        Registry.GetService<ISomeInterface>().RequiredMethod();
        

      这里的注册类是自定义创建的,它只保存实例并在必要时返回。 所有类都应该引用接口。 当您希望多个项目互操作时,此解决方案更有效。

      【讨论】:

        【解决方案4】:

        虽然我更喜欢事件和委托的技术,但我展示了另一种解决方案。

        var mainWnd = Application.Current.MainWindow as MainWindow;
        if(mainWnd != null)
           mainWnd.Navigate(new MyPage1());
        

        【讨论】:

        • 这没有回答问题
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-06
        相关资源
        最近更新 更多