Reputation: 22956
I have a button control which requires adding a handler to its root:
Application.Current.RootVisual.AddHandler( UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler( RootClicked ), true );
The problem is that when I do this the RootVisuual UIElement never destroys itself because of reference being created.
Is there a way for me to check when the RootVisual is no longer visible so I can dereference the event tied into it or at least in some other way dynamically remove the handle?
I've tried looking into weak events but the classes to implement that doesn't exist in silverlight..
With Weakreferences I've tried the following:
m_clickEventHandler = new MouseButtonEventHandler( RootClicked );
m_weakRefToRoot = new WeakReference( Application.Current.RootVisual );
( m_weakRefToRoot.Target as UIElement ).AddHandler( UIElement.MouseLeftButtonDownEvent, m_clickEventHandler, true );
Upvotes: 1
Views: 649
Reputation: 189485
Don't try mucking about with WeakReferences its a difficult thing to get right. tam was on the right track, use the unloaded event. True UIElement
doesn't have such an event but your logon page will be something that ultimately derives from FrameworkElement
. Hence:-
Delegate clickedHandler = new MouseButtonEventHandler( RootClicked );
FrameworkElement root = (FrameworkElement)Application.Current.RootVisual;
RootedEventHandler unloadHandler = null;
unloadHandler = (s, args) =>
{
root.Unloaded -= unloadHandler;
root.RemoveHandler(UIElement.MouseLeftButtonDownEvent, clickedHandler);
};
root.AddHandler( UIElement.MouseLeftButtonDownEvent, clickedHandler , true );
root.Unloaded += unloadHandler;
Upvotes: 2
Reputation: 12093
http://msdn.microsoft.com/en-us/library/system.weakreference(v=vs.95).aspx
WeakReference is available in Silverlight 3,4. Should be a solution for your problem.
Also, I am not aware of silverlight 3.5
Upvotes: 1