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 ?
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.