问题描述
我的要求:每个页面都需要一个会话计时器(登录页面除外)。如果计时器超过60秒且未执行任何用户操作,则应重定向到登录页面。
My Requirement : Need a session timer for every page(Except login page). If timer exceeded 60 seconds with no user actions performed, it should redirect to the login page.
我已成功完成上述一个页面的要求,其中包含以下代码段。
I have successfully done the above requirement for one page with below code snippets.
DispatcherTimer dispatcherTimer;
DateTimeOffset startTime;
DateTimeOffset lastTime;
DateTimeOffset stopTime;
int timesTicked = 1;
int timesToTick = 60;
page_load()
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
startTime = DateTimeOffset.Now;
lastTime = startTime;
dispatcherTimer.Start();
}
private void PhoneApplicationPage_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
{
startTime = DateTimeOffset.Now;
lastTime = startTime;
dispatcherTimer.Start();
}
void dispatcherTimer_Tick(object sender, object e)
{
DateTimeOffset time = DateTimeOffset.Now;
TimeSpan span = time - lastTime;
lastTime = time;
timesTicked++;
if (timesTicked > timesToTick)
{
isTimeOver = true;
stopTime = time;
dispatcherTimer.Stop();
span = stopTime - startTime;
MessageBox.Show("Login again", "Session Expired", MessageBoxButton.OK);
NavigationService.Navigate(new Uri("/Login_3.xaml", UriKind.Relative));
}
}
我需要每个页面都有这个逻辑。由于在导航的自定义类中无法访问页面,我很困惑。我不认为在每个页面中编写dispatcherTimer_Tick事件
是很好的方法。你能不能请任何人建议我们如何在一个可以用于每个页面的代码中执行此操作?在此先感谢:)
I need this logic for every pages. As pages are not accessible in custom classes for navigation, i am confused. I don't think writing dispatcherTimer_Tick event in every page is good approach. Could you please anyone advice how we can do this in onecode that can be used for every page? Thanks in advance:)
推荐答案
你可以创建自己的MyBasePage类派生自Windows.UI.Xaml.Controls.Page,在那里实现你的逻辑并在每个页面派生自你的MyBasePage之后(这是OOP的基本概念之一,代码重用)。
You can create your own MyBasePage class derived from Windows.UI.Xaml.Controls.Page , implement your logic there and after each page derive from your MyBasePage (this is one of the basic concepts of OOP, code reuse) .
这篇关于Windows Phone - 应用程序级DispatcherTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!