4

I have a dependency property (bool) which enables a behavior in a textbox. The property changed callback subscribes to some eventhandlers:

static void MyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is TextBox && e.NewValue != null)
        {
            var tb = d as TextBox;

            if ((bool)e.NewValue)
            {
                tb.Loaded += TextBox_OnLoaded;
                tb.MouseLeftButtonDown += TextBox_OnMouseLeftButtonDown;
            }
            else
            {
                tb.Loaded -= TextBox_OnLoaded;
                tb.MouseLeftButtonDown -= TextBox_OnMouseLeftButtonDown;
            }
        }
    }

in my Xaml, i have:

<TextBox
        customdp:MyTextBoxBehavior.EnableBehavior="True">
</TextBox>

Leaving this, the behavior works fine. But the unsubscribing never is executed! So Where do I have to put:

customdp:MyTextBoxBehavior.EnableBehavior="False"

???

Here is another case: 2) I have a listview and subscribed inside OnLoaded() to events of sub items in the visual tree. Reason: I don't want to add attached properties to each listviewitem.

static void ListView_OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        var lv = sender as ListView;
        if (lv != null)
        {
            foreach (TextBox tb in lv.Items)
            {
                 tb.LostFocus += TextBox_OnLostFocus;
            }
        }
    }

Idea: unsibscribe in:

ListView_OnUnLoaded(..)
{
   // Items already empty 
}

...where to unsubscribe ?

deafjeff
  • 754
  • 7
  • 25
  • Why and when do you want to unsubscribe? The only reason which I can figure out is closing window? – Wojciech Kulik Jun 26 '13 at 13:51
  • The windows are inside a TabControl with 1..n Tabs, and can be dynamically created and closed. So I guess I need to unsubscribe for garbage collection. – deafjeff Jun 26 '13 at 14:55
  • So why won't you do unsubscribe when tab is closing? – Wojciech Kulik Jun 26 '13 at 15:19
  • 1
    i have no access to the tab closing code, it is in another module. The unsubscribe must be in the behavior. Therefore I try to catch events like "UnLoaded" that tell me the UIElement is going to get removed from the visual tree. In My case above, the child items, from which I want to unsubscribe, are already removed, and I can't remove the handler then. – deafjeff Jun 27 '13 at 07:36
  • I also use the Unloaded and works fine (Y) – EricG Jul 27 '17 at 10:11

1 Answers1

0

At the moment where you are able to do tb.Loaded += you also have access to tb.Unloaded. Use that opportunity to add your cleanup code which will unsubscribe the Loaded event -- and also the Unloaded event.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81