How to Unsubscribe/ReSubscribe Dockpane from Event

703
1
10-24-2017 03:37 PM
MKa
by
Frequent Contributor

I have a Dock pane, that when it closes, i want to remove the selection changed event.  Then when i reopen it, I want to resubscribe.  Is there a better way to do this than by tracking the subscribed with a boolean?  I don't want it on when the dockpane is hidden, but i want it to be available again when I bring the pane back to showing.  I can't seem to simply unsubscribe and resubscribe like i want because OnShow gets called like 3 times when the pane is loaded and adds multiple Subscribes.

protected AttributeEditorViewModel()
{
      MapSelectionChangedEvent.Subscribe(OnMapSelectionChanged);
      subscribed = true;
}
~AttributeEditorViewModel()
{
      MapSelectionChangedEvent.Unsubscribe(OnMapSelectionChanged);
      subscribed = false;
}

protected override void OnHidden()
{
   if (subscribed)
   {
      MapSelectionChangedEvent.Unsubscribe(OnMapSelectionChanged);
      subscribed = false;
   }
}

protected override void OnShow(bool isVisible)
{
   if (!isVisible || subscribed)
   {
      MapSelectionChangedEvent.Unsubscribe(OnMapSelectionChanged);
      subscribed = false;
}
else
{
      MapSelectionChangedEvent.Subscribe(OnMapSelectionChanged);
      subscribed = true;
}
}

Tags (1)
0 Kudos
1 Reply
UmaHarano
Esri Regular Contributor

Hi

By using subscription tokens you can subscribe\unsubscribe when the dockpane is visible\hidden. This code below worked for me:

private SubscriptionToken _eventToken = null;
        protected override void OnShow(bool isVisible)
        {
            if (isVisible && _eventToken == null)
            {
                _eventToken = MapSelectionChangedEvent.Subscribe(OnMapSelectionChangedEvent);
            }

            if (!isVisible && _eventToken != null)
            {
                MapSelectionChangedEvent.Unsubscribe(_eventToken);
                _eventToken = null;
            }
        }

        private void OnMapSelectionChangedEvent(MapSelectionChangedEventArgs obj)
        {
            MessageBox.Show("Selection has changed");
        }

Thanks

Uma

0 Kudos