Search code examples
c#.netwinui-3winui

How to use Microsoft.UI.Xaml.Controls.Frame.Navigate


I have a question regarding Microsoft's WinUI Gallery implementation. In the NavigationRootPage.xaml.cs file, there is a method defined as follows:

public void Navigate(
    Type pageType,
    object targetPageArguments = null,
    Microsoft.UI.Xaml.Media.Animation.NavigationTransitionInfo navigationTransitionInfo = null)
{
    NavigationRootPageArgs args = new NavigationRootPageArgs();
    args.NavigationRootPage = this;
    args.Parameter = targetPageArguments;
    rootFrame.Navigate(pageType, args, navigationTransitionInfo);
}

The rootFrame.Navigate(pageType, args, navigationTransitionInfo); line uses the variable args, which is of type NavigationRootPageArgs. The definition of NavigationRootPageArgs is as follows:

public class NavigationRootPageArgs
{
    public NavigationRootPage NavigationRootPage;
    public object Parameter;
}

According to Microsoft's official documentation, the parameter for the Navigate method is described as:

parameter
Object
The navigation parameter to pass to the target page; must have a basic type (string, char, numeric, or GUID) to support parameter serialization using GetNavigationState.

Given this, how can this definition work with the Navigate method? Additionally, are there any other workable implementations for this scenario?

I consulted ChatGPT and looked through some similar code on GitHub, but I haven't found anything helpful so far. I was expecting to understand how the NavigationRootPageArgs type can work with the Navigate method despite the documentation stating that the parameter should have a basic type (string, char, numeric, or GUID) to support parameter serialization using GetNavigationState.


Solution

  • As the doc says:

    The navigation parameter to pass to the target page; must have a basic type (string, char, numeric, or GUID) to support parameter serialization using GetNavigationState.

    So, "to support parameter serialization using GetNavigationState", the parameter needs to be a basic type.

    The doc also says:

    The parameter value can have a complex type if you do not use GetNavigationState.

    The WinUI Gallery passes a NavigationRootPageArgs as the parameter value to initialize the target page by overriding OnNavigatedTo.