WinUI3导航报错‘Object reference not set to an instance of an object’求助
WinUI3导航报错:Object reference not set to an instance of an object.
问题场景
WinUI3新手,刚实现按钮事件响应,复制WinUI3 Gallery的导航代码后无法正常工作,点击按钮触发Button_Click时抛出Object reference not set to an instance of an object.错误。已确认MainFrame是有效实例,但问题仍存在。
现有代码
MainWindow.xaml:
<Window x:Class="safesign_win.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:safesign_win" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Frame x:Name="MainFrame"> <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center"> <Frame x:Name="TheNavFrame" /> <Button Click="Button_Click">Next</Button> </StackPanel> </Frame> </Window>
MainWindow.xaml.cs:
namespace testapp { public sealed partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { MainFrame.Navigate(typeof(BlankWindow1), null, new SlideNavigationTransitionInfo() { Effect = SlideNavigationTransitionEffect.FromRight }); // 错误发生在此行 } } }
问题分析
- 命名空间不一致:XAML中
x:Class指定的命名空间是safesign_win,但C#代码的命名空间是testapp,这会导致控件绑定的潜在上下文异常。 - 导航目标类型错误:
Frame.Navigate()仅支持导航到Page类型,而你尝试导航的BlankWindow1是Window类型,这会触发空引用异常。 - Frame结构不合理:主
MainFrame直接将StackPanel作为Content,不符合Frame导航的常规用法,Frame的Content应该是Page实例而非布局控件。
解决方案
1. 统一命名空间
将C#代码的命名空间改为与XAML一致:
namespace safesign_win { public sealed partial class MainWindow : Window { // 其余代码不变 } }
2. 替换导航目标为Page
创建BlankPage1(Page类型)作为导航目标;若需打开新窗口,改用窗口激活方式:
// 导航到Page(推荐) MainFrame.Navigate(typeof(BlankPage1), null, new SlideNavigationTransitionInfo() { Effect = SlideNavigationTransitionEffect.FromRight }); // 打开新窗口(替代方案) new BlankWindow1().Activate();
3. 调整Frame布局结构
重构XAML布局,让MainFrame作为专门的导航容器:
<Window x:Class="safesign_win.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:safesign_win" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Button Grid.Row="0" Click="Button_Click" Margin="10" HorizontalAlignment="Center">Next</Button> <Frame x:Name="MainFrame" Grid.Row="1"/> </Grid> </Window>
4. 初始化Frame导航(可选)
在窗口构造函数中设置初始页面,确保导航上下文正常:
public MainWindow() { this.InitializeComponent(); // 导航到自定义初始页面(如HomePage) MainFrame.Navigate(typeof(HomePage)); }
内容的提问来源于stack exchange,提问作者PaytonDEV
相关产品推荐
相关产品推荐

