Razor
Razor

Reputation: 689

Getting the Dispatcher of a Window in UWP

Here are some of the ways to get the dispatcher of the view.

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher

and

Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().CoreWindow.Dispatcher

While the first one returns the dispatcher of the mainview, and the latter returns the dispatcher of the active view, How can I get the dispatcher of a view which is not active?

Upvotes: 1

Views: 5478

Answers (2)

MoDu
MoDu

Reputation: 106

After some recent experience, I would suggest against storing references to Dispatchers. Instead, rely on the page/control you want to run the UI code, as every XAML control has their own CoreDispatcher. That way, you are sure you have the correct dispatcher and if it is missing, it's a sign that something is wrong. Code from xaml source:

namespace Windows.UI.Xaml
{
//Summary:
//Represents an object that participates in the dependency property system. DependencyObject is the immediate base class of many `enter code here` important UI-related classes, such as UIElement, Geometry, FrameworkTemplate, Style, and ResourceDictionary.
public class DependencyObject : IDependencyObject, IDependencyObject2
{

    //Summary:
    //Gets the CoreDispatcher that this object is associated with. The CoreDispatcher represents a facility that can access the DependencyObject on the UI thread even if the code is initiated by a non-UI thread.
    // Returns: The CoreDispatcher that DependencyObject object is associated with, which represents the UI thread.
    public CoreDispatcher Dispatcher { get; }

(...)

}
}

Upvotes: 2

DevAttendant
DevAttendant

Reputation: 636

You need to have a reference to the view you want to access the Dispatcher from. If you create you save it somehow, see below. Alternatively you can access all views by calling this:

IReadOnlyList<CoreApplicationView> views = CoreApplication.Views;

However a view does not have a directly accessible identifier, so you need to fetch an identifier by calling the following after the view has been activated in a dispatcher for it:

await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
    Frame frame = new Frame();
    frame.Navigate(typeof(SecondaryPage), null);   
    Window.Current.Content = frame;
    // You have to activate the window in order to show it later.
    Window.Current.Activate();

    newViewId = ApplicationView.GetForCurrentView().Id;
});

Then I would suggest to create your own IDictionary<int, CoreApplicationView> to have a mapping between ids and your views. Alternatively you can also get the id by

newViewId = ApplicationView.GetApplicationViewIdForWindow(newView.CoreWindow);

(some further documentation)

Upvotes: 2

Related Questions