如何订阅事件在正常运行的Windows应用程序? [英] How to subscribe to events properly in Windows Runtime apps?

查看:187
本文介绍了如何订阅事件在正常运行的Windows应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我同意 OrientationChanged 事件在这样的构造:

I subscribe to OrientationChanged event in the constructor like this:

public SecondPage()
{
    this.InitializeComponent();

    deviceOrientationSensor = SimpleOrientationSensor.GetDefault();

    if (deviceOrientationSensor != null)
    {
        deviceOrientationSensor.OrientationChanged += OrientationChanged;
    }
}

和则:

private void OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args)
{
    deviceOrientation = args.Orientation;
    // the rest...
}



所以,问题是,当我浏览再换另一页,或进入到手机开始屏幕,在下一次处理 OrientationChanged 事件两次,一次3次,依此类推。

So the problem is that when I navigate back to another page or go to the phone start screen, the next time it handles OrientationChanged event twice, and again for 3 times and so on.

似乎再次预订了事件,而不移除先前的订阅。它不仅发生了方向变化的事件,但对于任何其它事件了。

it seems it subscribes to the event again without removing previous subscription. It happens not only for orientation change event, but for any other event too.

我想我可以在 OnNavigatedFrom 方法,但它似乎不保证不像以前的Windows Phone Silverlight应用程序的情况发生。

I thought I can unsubscribe on OnNavigatedFrom method, but it seems it is not guaranteed to happen unlike previous Windows Phone Silverlight apps.

如何防止多个订阅?谢谢。

How to prevent multiple subscriptions? thanks.

推荐答案

1),在页面中不要订阅,但在App.Xaml.cs代替。

1) Don't subscribe in the pages, but in App.Xaml.cs instead.

2)取消订阅的OnNavigatedFrom方式:

2) Unsubscribe in the OnNavigatedFrom method:

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
  deviceOrientationSensor.OrientationChanged -= OrientationChanged;
}

这篇关于如何订阅事件在正常运行的Windows应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆