2015-04-22 59 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,並與它一起去。 讓我知道它是否適合你。