views:

29

answers:

1

Hi,

We have a few scenarios in our WPF/MVVM application where a window is being instanciated and opened within the confines of a method. Very simplistic example:

Private Sub subOpenWindow
    Dim myViewModel = New Viewmodel1 'create viewmodel that Window1 will use as datacontext
    AddHandler myViewModel.SomeEvent, AddressOf subHandleSomeEvent

    Dim myWindow = New Window1(ViewModel1)
    myWindow.Show
End Sub

Private Sub subHandleSomeEvent
 'do some stuff
End Sub

Now - we are debating whether or not the use of an AddHandler without a subsequent RemoveHandler (normally a big no-no) is causing us memory issues given that the AddHandler declaration is decalred and used inside of the subOpenWindow method and there is no obvious means of performing a RemoveHandler call. We could move the viewmodel declaration to a more global level but this does not seem as clean.

The question is: is a RemoveHandler necessary in this scenario? Or will garbage collection clean up properly once the window has been closed?

A: 

You could handle the Window's Closed event to remove the handler. As it is, the reference created by the current class (the one containing the handler) does indeed keep myViewModel in memory. An alternative would be to look into using weak events - see here for details.

Alex Paven
Thanks Paven - in the end we've added a bit more logic to the child viewmodel/parent viewmodel relationship and are now simply issuing the RemoveHandler when the child uc/vm is being closed.
Gatmando