【问题标题】:Communicate between pages in wpfwpf中页面之间的通信
【发布时间】:2015-04-22 15:57:28
【问题描述】:

我有两个页面和一个主窗口..我在两个框架中加载页面..现在我想执行彼此的方法..我该怎么做?

这是 Page1.cs:

public partial class Page1 : Page
{
    public Method1()
    {
        doSomething;            
    }
}

这是 Page2.cs:

public partial class Page2 : Page
{
    public Method2()
    {
        doSomethingElse;            
    }
}

在我的 MainWindow 中会发生以下情况:

Frame1.Source = new Uri("/Source/Pages/Page1.xaml", UriKind.RelativeOrAbsolute);
Frame2.Source = new Uri("/Source/Pages/Page2.xaml", UriKind.RelativeOrAbsolute);

有什么办法,从Page1.cs执行Method2,从Page2.cs执行Method1?

问候

【问题讨论】:

    标签: c# wpf frames communicate


    【解决方案1】:

    一种方法是通过它们的共同父级窗口。

    看这个(相应修改)

    public partial class MainWindow : Window
    {
        public Page1 Page1Ref = null;
        public Page1 Page2Ref = null;
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Frame1.Source = new Uri("/Source/Pages/Page1.xaml", UriKind.Relative);
            Frame1.ContentRendered += Frame1_ContentRendered;
    
            // do the same for the Frame2
        }
    
        private void Frame1_ContentRendered(object sender, EventArgs e)
        {
            var b = Frame1.Content as Page1; // Is now Home.xaml
            Page1Ref = b;
            if(Page2Ref != null) // because you don't know which of the pages gets rendered first
            {
               Page2Ref.Page1Ref = Page1Ref; // add the Page1Ref prop to your Page2 class 
               Page1Ref.Page2Ref = Page2Ref;  // here the same
            }
    
        }
        // do the same for the other page
    }
    

    来自this question

    一旦页面加载到另一个页面,您应该能够设置引用。

    更好的是,您可能希望让 Pages 知道其窗口父级并通过它访问另一个页面。无论哪种方式,都是糟糕的设计,我告诉你。

    这不是一个值得骄傲的解决方案,您最好查看MVVM,然后继续使用它。 让我知道它是否对你有用。

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多