问题
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