Home > OS >  Change view using a button click in WinUI 3
Change view using a button click in WinUI 3

Time:06-24

In WinUI 3 I want to change the view to a SecondaryView after a button click. The view change works flawlessly if I just add it to my code. But as soon as it happens in a Button Click function the app crashes. I am using the Template Studio for WinUI template to do this. The relative code is as follows:

MainPage.xaml:

<Grid x:Name="ContentArea">
   <TextBlock Text="Main Page"/>
   <Button Content="Press" Click="Button_Clicked"/>
</Grid>

MainPage.xaml.cs

private readonly INavigationService _navigationService;
public MainPage()
{
    ViewModel = App.GetService<MainViewModel>();
    InitializeComponent();
    _navigationService.NavigateTo(typeof(SecondaryViewModel).FullName); // WORKS
}

private void Button_Clicked(object sender, RoutedEventArgs e)
{
    _navigationService.NavigateTo(typeof(SecondaryViewModel).FullName); // DOESN'T WORK
}

The exception I get is

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
     UnhandledException  = (sender, e) =>
     {
          if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
     };
#endif

This is all right from the template, barely changing anything. I tried it in my own code first before trying the template and got the same error. Is there any way to change the view on a button click?

CodePudding user response:

You need to initialize the _navigationService.

public sealed partial class MainPage : Page
{
    private readonly INavigationService _navigationService;

    public MainViewModel ViewModel
    {
        get;
    }

    // Constructor
    public MainPage()
    {
        ViewModel = App.GetService<MainViewModel>();
        InitializeComponent();
        _navigationService = App.GetService<INavigationService>();  // This line is missing.
        _navigationService.NavigateTo(typeof(SecondaryViewModel).FullName);
    }

    private void Button_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
    {
        _navigationService.NavigateTo(typeof(SecondaryViewModel).FullName);
    }
}
  • Related