我应该在哪里取消注册XAML行为中的事件?

时间:2018-01-09 16:00:49

标签: xaml uwp behavior

在XAML行为类中,哪里应该是取消注册事件的最佳位置?我应该在已卸载事件中取消注册,还是应该在检测时执行此操作?

  public class ShowKeyboardOnFocusBehavior : Behavior<TextBox>
  {

    protected override void OnAttached()
    {
      base.OnAttached();
      AssociatedObject.Loaded += AssociatedObject_Loaded;
      AssociatedObject.GotFocus += AssociatedObject_GotFocus;
      AssociatedObject.Unloaded += AssociatedObject_Unloaded;
    }

    private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
    {
      AssociatedObject.Loaded -= AssociatedObject_Loaded;
      AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
      AssociatedObject.Unloaded -= AssociatedObject_Unloaded; 
    }

    protected override void OnDetaching()
    {
      AssociatedObject.Loaded += AssociatedObject_Loaded;
      AssociatedObject.GotFocus += AssociatedObject_GotFocus;
    }
...

1 个答案:

答案 0 :(得分:2)

您应该使用OnDetaching取消注册您的活动。将始终调用此方法,这是Microsoft的官方UWP行为库中使用的方法(请参阅for example EventTriggerBehavior)。

它曾经是一个问题(相关对象被卸载但行为仍留在内存中)但它现在在库内被考虑,所以你肯定会知道Detach将被调用(你可以看到)它自己在Microsoft.Xaml.Interactivity.Interaction source code

中的FrameworkElement_Unloaded方法中