How to subscribe to events properly in Windows Runtime apps?

旧巷老猫 提交于 2019-12-23 04:54:29

问题


I subscribe to OrientationChanged event in the constructor like this:

public SecondPage()
{
    this.InitializeComponent();

    deviceOrientationSensor = SimpleOrientationSensor.GetDefault();

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

and then:

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

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.

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:


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

2) Unsubscribe in the OnNavigatedFrom method:

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


来源:https://stackoverflow.com/questions/26285471/how-to-subscribe-to-events-properly-in-windows-runtime-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!