4

これがシナリオです。私は3つ持っていますxaml

  • メインウィンドウ
  • ページ1
  • ページ2

MainWindow の下に、「Page1」という名前のボタンと「Frame1」という名前のフレームがあります。

コード:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.
  Dim page1 As New Page1
  Frame1.Navigate(page1)
End Sub

したがって、Page1.xaml「Frame1」に表示されます

次にPage1.xaml、「Page2」という名前の別のボタンがあります

コード:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
  Dim p2 As New page2
  Dim main As New MainWindow

  main.Frame1.Navigate(p2)
End Sub

「Frame1」内および「MainWindow」内にある「Page1」内のボタンをクリックしても、フレームは変更されません。

私は何かが欠けていると思います...

4

1 に答える 1

1

基本的に、問題は、既存のメイン ウィンドウを参照するのではなく、ボタン 1 のクリック イベントで新しいメイン ウィンドウをインスタンス化しているように見えます。そのため、実際に Frame1 Navigate メソッドを呼び出している間、実際にはまったく別のウィンドウでそれを実行しているため、たまたま非表示になっています。

必要なことは、Page1 の親 MainWindow への参照を見つけることです。これにはいくつかの方法があります。

  • ルーティング イベントを使用して Page1 から発生させ、MainWindow で処理することができます。
  • Page1 にパブリック プロパティを作成し、Page1 の作成時にそれを MainWindow インスタンスに渡します。
  • Page1 から始まり、MainWindow が見つかるまでビジュアル ツリーをクロールしてから、ナビゲーションを行うこともできます。以下のコードでそれを示します。

ページ 1 の XAML

<Page x:Class="WpfApplication1.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="Page1">

    <Grid>
        <Button HorizontalAlignment="Center"
                VerticalAlignment="Bottom"
                Click="Page2Button_Click"
                Content="Page 2" />
    </Grid>
</Page>

ページ 1 の分離コード

using System.Windows;
using System.Windows.Media;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class Page1
    {
        public Page1()
        {
            InitializeComponent();
        }

        private void Page2Button_Click(object sender, RoutedEventArgs e)
        {
            var mainWindow = GetParentWindow(this);
            if (mainWindow != null) mainWindow.Frame1.Navigate(new Page2());
        }

        private static MainWindow GetParentWindow(DependencyObject obj)
        {
            while (obj != null)
            {
                var mainWindow = obj as MainWindow;
                if (mainWindow != null) return mainWindow;
                obj = VisualTreeHelper.GetParent(obj);
            }
            return null;
        }
    }
}
于 2013-02-08T13:29:27.980 に答える