我正在将一个应用程序从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,我在导航例程中设置了标记以跟踪当前视图。我想把这个烂摊子改对。
下一步是如何实际更改字段。
我在XAML代码后面有一个例程,用于设置字段
public void SetFieldsTick(bool spot)
{
UTC_Data.Text = Vars.DateStrZ;
}
如果我想从我的后台例程引用这个,那么这个例程必须是静态的。如果我做了这个更改,那么例程就不能引用页面上的字段,因为它们不是静态的。
我知道这可能是显而易见的,但我被难住了。
提前谢谢。
您使用的Timer将提供一种机制,用于以指定的间隔在线程池线程上执行方法。它在一个单独的线程上运行。所以,若您想处理应用程序的UI,它需要在UI的调度器线程上运行。在这种情况下,可以使用Dispatcher.RunAsync方法对UI线程进行回调。例如:
App.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);
}
}