xaml - UWP 从后台更新当前窗口
问题描述
我正在将应用程序从 WinRT 移植到 UWP。(我已经将它移植到 iOS 和 Android 上)
我的应用程序有多个页面。我需要能够确定当前查看的是哪个页面,然后更新内容。(由于各种原因,DataBinding 不是一个选项。)
我有一个在后台运行的例程(而不是在 UI 线程上),从调度计时器中调用。
在 WinRT 中,我处理如下:
// If current window is MainPage, then update the displayed fields
var _Frame = Window.Current.Content as Frame;
Page _Page = _Frame.Content as Page;
if (_Page is MainPage)
{
MainPage _XPage = _Frame.Content as MainPage;
_XPage.SetFieldsTick(spoton);
}
由于 UWP 为 Windows.Current.Content 返回 null,因此我在 Navigation 例程中设置了标志以跟踪当前视图。我想正确地解决这个问题。
下一步是如何实际更改字段。
我在 XAML 代码后面有一个例程来设置字段
public void SetFieldsTick(bool spot)
{
UTC_Data.Text = Vars.DateStrZ;
}
如果我想从我的后台例程中引用它,那么例程必须是静态的。如果我进行此更改,则例程无法引用页面上的字段,因为它们不是静态的。
我知道这可能是显而易见的,但我很难过。
提前致谢。
解决方案
您使用的Timer将提供一种机制,用于以指定的时间间隔在线程池线程上执行方法。它在单独的线程上运行。因此,如果您想处理应用程序的 UI,它需要在 UI 的调度程序线程上运行。在这种情况下,您可以使用Dispatcher.RunAsync方法在 UI 线程上进行回调。例如:
应用程序.xaml.cs:
public void StartTimer()
{
DateTime startTime;
startTime = DateTime.UtcNow;
var dispatcherTimer = new System.Threading.Timer(DispatcherTimer_Tick, startTime, 0, 1000);
}
private async void DispatcherTimer_Tick(object state)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var _Frame = Window.Current.Content as Frame;
Page _Page = _Frame.Content as Page;
if (_Page is MainPage)
{
MainPage _XPage = _Frame.Content as MainPage;
_XPage.SetFieldsTick(true);
}
});
}
此外,建议使用DispatcherTimer,它可用于在产生 UI 线程的同一线程上运行代码。在这种情况下,您不需要在 UI 线程上进行回调。
public void StartTimer()
{
var dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, object e)
{
var _Frame = Window.Current.Content as Frame;
Page _Page = _Frame.Content as Page;
if (_Page is MainPage)
{
MainPage _XPage = _Frame.Content as MainPage;
_XPage.SetFieldsTick(true);
}
}
推荐阅读
- python - Google IAP 不断响应 401 Unauthorized
- c++ - 带括号的“嵌套”类模板参数推导:GCC 与 clang
- javascript - Html to JS Datatable:排序或页面大小更改后仍显示删除的行?
- assembly - x86 汇编助记符是否标准化?
- c# - 如何在 .net core 2.2 控制台应用程序中实现依赖注入
- python - 如何在同一根目录但在不同的子目录中导入 Python 模块?
- parsing - 如何在 prolog 中编写解析器以输出解析树
- reactjs - 根据 Mobx 状态设置本地状态
- sql-server - SQL - 合并两列,优先选择其中之一,同时记录原始源
- objective-c - 禁止在 macOS 应用程序启动时打开文件