2015-04-22 62 views
2

我有两个页面和一个MainWindow ..我在两个框架中加载页面..现在我想执行彼此的方法..我怎么能做到这一点?wpf中的页面之间的通信

这是Page1.cs:

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

这是Page2.cs:

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

在我的主窗口会发生以下情况:

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?

Regards

回答

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

你应该能够设置一个参考。

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

是不是一个值得自豪的解决方案,你可以更好地研究MVVM,并与它一起去。 让我知道它是否适合你。