How to access XamlRoot from a non-UI thread?

59 views Asked by At

I am making a WASDK WinUI 3 app. In my App.xaml.cs, I have this:

public static XamlRoot AppXamlRoot { get; set; }

Then, on my main window, I've got this:

private void MainGrid_Loaded(object sender, RoutedEventArgs e)
{
    App.AppXamlRoot = this.Content.XamlRoot;
}

MainGrid is a Grid element in the XAML code. Finally, on a ViewModel class, I have an async method that uses the App.AppXamlRoot, which should be accessible because it is static and App class declaration is accessible from the whole C# project. In my async method, the App.AppXamlRoot throws a COM exception.

await MyMessageBox.Show($"{ex.Message}\n\n{ex.InnerException}", App.AppXamlRoot);
1

There are 1 answers

0
Andrew KeepCoding On

If you need to access the UI from a non-UI thread, you need to use the DispatcherQueue.

For example, in your App.xaml.cs:

public static DispatcherQueue DispatcherQueue { get; } = DispatcherQueue.GetForCurrentThread();

and use it like this:

App.DispatcherQueue.TryEnqueue(async () =>
{
    // Acceess the UI here...
}