页面框架内的 WPF 按钮导航以更改父页面

WPF Button within a frame in a page navigates to change the parent page

我对 WPF 还很陌生,但现在真的很喜欢它。我对要实现的页面导航有疑问。

我有一个 MainWindow.xaml,里面有一个框架。 启动时,框架加载第 1 页。 第 1 页有一个按钮。 如果单击该按钮,第二页将出现在框架内。 但是,我不想要这个。当用户单击第 1 页中的按钮时,我希望整个页面(MainWindow.xaml) 导航到第 2 页。因此我需要更改实际的父页面本身。

我在按钮的 Click 事件中使用了以下代码。就是不知道父页面怎么引用。

private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new PageTwoReplacesMainPage());
        }

如果我需要提供更多信息,请告诉我。 我希望这是有道理的,任何帮助将不胜感激。谢谢。

MainWindow.xaml 代码是...

<Window x:Class="TestWpfParentNavigation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWpfParentNavigation"
        mc:Ignorable="d"
        Title="MainWindow" MinHeight="500" MinWidth="700" Background="Beige">
    <Grid>
        <StackPanel>
            <Frame x:Name="myMainFrame" NavigationUIVisibility="Hidden" Height="400" Width="600" Margin="0,50,0,0" />
        </StackPanel>
    </Grid>
</Window>

Page1.xaml 是...

<Page x:Class="TestWpfParentNavigation.PageOneWithButton"
      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" 
      xmlns:local="clr-namespace:TestWpfParentNavigation"
      mc:Ignorable="d" 
      d:DesignHeight="200" d:DesignWidth="300"
      Title="PageOneWithButton" Background="Bisque">

    <Grid>
        <Button Content="Go to the second page" Height="30" Width="150" Click="Button_Click" Margin="10,10,140,160" />
    </Grid>
</Page>

Page2.xaml 是...

<Page x:Class="TestWpfParentNavigation.PageTwoReplacesMainPage"
      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" 
      xmlns:local="clr-namespace:TestWpfParentNavigation"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="PageTwoReplacesMainPage" Background="Aqua">

    <Grid>

    </Grid>
</Page>

我找到了答案。我误解了 Window 的工作方式。

为了解决我的问题,我做了以下事情:

在MainWindow.xaml中,我创建了一个覆盖整个window的框架。 然后我将页面加载到框架中。这个页面有第二个框架。 在第二帧中,我加载了具有按钮的第二页。 当我点击按钮时,我现在可以访问第一帧并导航到我想要的页面。这意味着我现在可以使用我的主页概念了。

感谢大家的帮助。你给了我理解我的问题并回答它的线索。亲切的问候。我希望这个答案有意义并对其他人有所帮助。