Quark Soup
Quark Soup

Reputation: 4741

How do you instantiate Pages that have constructors in UWP?

I want to use the Navigation feature in UWP. Unfortunately, the argument to the Navigate method is a type, not an instance of a page. It looks like the activation of this type is done behind the scenes. I question the design decision, but my immediate problem is that all my MVVM forms are instantiated with the view model. Typically I create pages using the Dependency Injection container.

How do you create pages in UWP when they're used with the Navigate method when those pages have DI constructors?

Upvotes: 3

Views: 1010

Answers (2)

mm8
mm8

Reputation: 169320

How do you create pages in UWP when they're used with the Navigate method when those pages have DI constructors?

Instead trying to navigate to the page based on its type, you could set the Content of the Frame to an instance that you create yourself:

rootFrame.Content = new YourPage(yourDependency);

The other option is to make sure that all your pages have a default parameterless constructor and inject the dependencies somewhere else, for example in the OnNavigatedTo method as suggested by @Richard Zhang - MSFT.

Upvotes: 2

Anran Zhang
Anran Zhang

Reputation: 7727

In UWP, the navigation parameters of Frame.Navigate are Type rather than instances. This is really a design.

In fact, navigating in UWP doesn't require instances, as well as DI, and in general, if you need to combine Page and ViewModel, you can do this:

1. Initialize ViewModel inside the page constructor

Frame

MyFrame.Navigate(typeof(MyPage));

MyPage

private MyViewModel vm;
public MyPage()
{
    this.InitializeComponent();
    vm = new MyViewModel();
}

2. Initialize ViewModel by passing parameters when navigating

Frame

var vm = new MyViewModel();
MyFrame.Navigate(typeof(MyPage), vm);

MyPage

private MyViewModel vm;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if(e.Parameter!=null && e.Parameter is MyViewModel _vm)
    {
        vm = _vm;
        // do other things
    }
}

If you want to reuse pages, you can enable page caching, it will save the current page state (including ViewModel), and use the cache when you next navigate to the page, so you can avoid repeatedly creating ViewModel.

public MyPage()
{
    this.InitializeComponent();
    NavigationCacheMode = NavigationCacheMode.Enabled;
}

Best regards.

Upvotes: 2

Related Questions