François
François

Reputation: 3274

UWP - How to pass in a non null XamlRoot of a page to a NavigationService called by ViewModel associated to the page?

In my UWP app MVVM implementation, my ViewModels do not know about their View.

My ViewModels call a NavigationService.DisplayAlert() method. I need the ContentDialog to be shown from the AppWindow of the page associated with the ViewModel.

To do so, I follow that documentation. I try to pass in the AppWindow XamlRoot to the ViewModel. However, whatever UIElement of the Page used for the AppWindow I take, it has a null XamlRoot. How come?

How can I pass in my AppWindow XamlRoot to its ViewModel?

In my NavigationService:

public async Task DisplayAlert(string message, object existingElementXamlRoot)
{
    var messageDialog = new ContentDialog
    {
        Title = "Message",
        Content = message,
        CloseButtonText = "Ok"
    };
    if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8) && existingElementXamlRoot is XamlRoot xamlRoot) messageDialog.XamlRoot = xamlRoot;
    await messageDialog .ShowAsync();
}

In my BasePage:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    DataContext = e.Parameter;
    ((IBasePageViewModel) DataContext).XamlRoot = this.Content.XamlRoot;//I cannot find any UIElement with a non null XamlRoot
    base.OnNavigatedTo(e);
}

Upvotes: 1

Views: 571

Answers (1)

dear_vv
dear_vv

Reputation: 2358

You have gotten the expected behavior. Page.OnNavigatedTo(NavigationEventArgs) method mentions “the OnNavigated method is called before the visual tree is loaded.” Therefore, you can’t expect to get xamlroot in OnNavigatedTo method.

I suggest you could do this in Loaded event of page, which works well.

Upvotes: 1

Related Questions