2

2 つの Pages と 1 つの MainWindow があります..Pages を 2 つの Frames にロードします..今、お互いからメソッドを実行したい..どうすればこれを行うことができますか?

これは 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 を実行する方法はありますか?

よろしく

4

1 に答える 1

1

これを行う 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
}

この質問から

ページが他のページに読み込まれると、参照を設定できるはずです。

さらに良いことに、ページにウィンドウの親を知らせ、それを介して他のページにアクセスすることもできます。いずれにせよ、悪い設計です、私はあなたに言っています。

は自慢できる解決策ではありませんMVVM。うまくいったかどうか教えてください。

于 2015-04-22T16:43:44.527 に答える