You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI 3中点击按钮跳转至其他页面的实现方法求助

在WinUI 3中实现按钮跳转页面的方法

基础按钮跳转:用Frame导航核心逻辑

如果是普通按钮跳转页面,核心是借助Frame控件的Navigate方法,步骤如下:

  1. 准备目标页面:先创建好要跳转的页面(比如MainPage和SecondPage),确保它们在项目中正常存在。
  2. 添加Frame容器:在主窗口(MainWindow.xaml)中添加Frame作为页面承载容器:
<Window
    x:Class="YourProjectName.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow">
    <Grid>
        <Frame x:Name="MainContentFrame" />
    </Grid>
</Window>
  1. 设置初始页面:在MainWindow.xaml.cs的构造函数里,给Frame设置默认显示的页面:
public MainWindow()
{
    this.InitializeComponent();
    MainContentFrame.Navigate(typeof(MainPage));
}
  1. 按钮点击触发跳转:在MainPage.xaml中添加按钮并绑定点击事件:
<StackPanel Padding="20">
    <Button Content="跳转到第二页" Click="NavigateToSecondPage_Click"/>
</StackPanel>

然后在MainPage.xaml.cs中实现跳转逻辑:

private void NavigateToSecondPage_Click(object sender, RoutedEventArgs e)
{
    // 获取主窗口的Frame控件
    var mainFrame = (App.Current.MainWindow.Content as Frame) ?? MainContentFrame;
    mainFrame.Navigate(typeof(SecondPage));
}

修复NavigationViewItem跳转失败问题

你之前用NavigationViewItem没成功,大概率是没正确处理NavigationView的选择事件,正确配置方式:

  1. 配置NavigationView与Frame:在XAML中设置NavigationView,并内置Frame作为页面容器:
<NavigationView x:Name="MainNavView"
                SelectionChanged="MainNavView_SelectionChanged">
    <NavigationView.MenuItems>
        <NavigationViewItem Content="主页" Tag="MainPage"/>
        <NavigationViewItem Content="第二页" Tag="SecondPage"/>
    </NavigationView.MenuItems>
    <!-- 用于承载页面的Frame -->
    <Frame x:Name="NavContentFrame"/>
</NavigationView>
  1. 处理选择事件实现导航:在后台代码中编写SelectionChanged事件逻辑:
private void MainNavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
    if (args.SelectedItem is NavigationViewItem selectedItem)
    {
        // 通过Tag匹配对应的页面类型
        var targetPage = selectedItem.Tag switch
        {
            "MainPage" => typeof(MainPage),
            "SecondPage" => typeof(SecondPage),
            _ => null
        };

        if (targetPage != null && NavContentFrame.CurrentSourcePageType != targetPage)
        {
            NavContentFrame.Navigate(targetPage);
        }
    }
}
  1. 设置初始选中项:在窗口构造函数中指定默认选中的导航项:
public MainWindow()
{
    this.InitializeComponent();
    MainNavView.SelectedItem = MainNavView.MenuItems[0];
    NavContentFrame.Navigate(typeof(MainPage));
}

额外提示

  • 如需传递参数给目标页面,可在Navigate方法中添加第二个参数,比如frame.Navigate(typeof(SecondPage), "自定义参数"),然后在目标页面的OnNavigatedTo方法中接收。
  • 若使用MVVM模式,可通过绑定ICommand命令来实现导航,避免直接在后台写事件逻辑。

内容的提问来源于stack exchange,提问作者Marcelsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:20:33