如何在Windows运行时应用程序中正确订阅事件?

时间:2014-10-09 18:24:01

标签: c# xaml windows-runtime windows-phone windows-phone-8.1

我在构造函数中订阅OrientationChanged事件,如下所示:

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次等等。

它似乎再次订阅该事件而不删除以前的订阅。它不仅适用于方向更改事件,也适用于任何其他事件。

我认为我可以取消订阅OnNavigatedFrom方法,但似乎不能保证与以前的Windows Phone Silverlight应用程序不同。

如何防止多次订阅?感谢。

1 个答案:

答案 0 :(得分:0)

1)不要在页面中订阅,而是在App.Xaml.cs中订阅。

2)取消订阅OnNavigatedFrom方法:

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