【问题标题】:Getting the Dispatcher of a Window in UWP在 UWP 中获取窗口的调度程序
【发布时间】:2016-12-15 20:43:57
【问题描述】:

这里有一些获取视图调度器的方法。

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

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

虽然第一个返回主视图的调度器,而后者返回活动视图的调度器, 如何获取未激活视图的调度程序?

【问题讨论】:

    标签: c# uwp win-universal-app ui-thread


    【解决方案1】:

    您需要引用要从中访问 Dispatcher 的视图。如果你创建你会以某种方式保存它,见下文。或者,您可以通过调用以下命令访问所有视图:

    IReadOnlyList<CoreApplicationView> views = CoreApplication.Views;
    

    但是,视图没有可直接访问的标识符,因此您需要在视图在调度程序中为其激活后调用以下代码来获取标识符:

    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;
    });
    

    然后我建议创建您自己的IDictionary&lt;int, CoreApplicationView&gt; 以在 id 和您的视图之间建立映射。或者,您也可以通过

    获取 id
    newViewId = ApplicationView.GetApplicationViewIdForWindow(newView.CoreWindow);
    

    (进一步documentation

    【讨论】:

      【解决方案2】:

      根据最近的一些经验,我建议不要存储对 Dispatchers 的引用。相反,依赖于您要运行 UI 代码的页面/控件,因为每个 XAML 控件都有自己的 CoreDispatcher。这样,您就可以确定您拥有正确的调度程序,如果它丢失,则表明有问题。来自 xaml 源的代码:

      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; }
      
      (...)
      
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        • 2016-08-20
        • 1970-01-01
        • 1970-01-01
        • 2018-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多