In WPF all controls inherit DispatcherObject & its easy to get to the Dispatcher.
How would I get the DispatcherQueue using WinUI 3 Windows App SDK and use it in a ViewModel?
EDIT
My implementation which expands on mm8's most appreciated answer.
Create a Property in my ViewModel
public Microsoft.UI.Dispatching.DispatcherQueue TheDispatcher { get; set; }
Then grab the dispatcher in my MainPage.xaml.cs codebehind Constructor
ViewModel.TheDispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();
Now I have the dispatcher n my VM so its easy to use from the VM:
TheDispatcher.TryEnqueue(() =>
{
// some ui thread work
});
Note: I didnt post this as an answer as there is one, this is my implementation to help anyone interested.
Call the DispatcherQueue.GetForCurrentThread()
API on the dispatcher thread.
If you create your view models on the dispatcher thread, you could call the method in the constructor or directly in the initializer as I demonstrated in your other question.
If you create your view models on a background thread, you will have to inject them with a DispatcherQueue
that you create before on an actual dispatcher thread, e.g.:
DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
Task.Run(() =>
{
ViewModel vm = new ViewModel(dispatcherQueue);
...
});