Search code examples
silverlightmvvm-lightchildwindow

Unload childwindow on close (silverlight mvvm)


How may I ensure that my childwindow is unloaded when it's closed?

I am opening the childwindow from my viewmodel, but after it's been closed it still fires of events like selectionchanged on comboboxes.

The childwindow is using the same viewmodel as it's been called from, so I guess that explains why the events are being fired. The itemssources are still valid.

But when it's closed, I would like to "dispose" the childwindow for good.

I've tried to add a Closed handler like this (Default view code behind):

    private void OnLaunchEditItem(ItemMessage msg)
    {
        var editWnd = new EditItemWindow();
        editWnd.Closed += new EventHandler(editWnd_Closed);
        editWnd.Show();
    }

    void editWnd_Closed(object sender, EventArgs e)
    {
        sender = null;
    }

No sucesss..

So what I'm doing now is to remove the itemssource from the childwindow controls, which seems to me... not the ideal solution to the problem. It must be possible to dispose it all from memory on closing? (Childwindow "view" code-behind)

    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
        combobox1.ItemsSource = null;
        combobox2.ItemsSource = null;
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = false;
        combobox1.ItemsSource = null;
        combobox2.ItemsSource = null;
    }

Solution

  • The messaging has a known problem that it introduces a hard link between the messenger and the recipient of a message. So if you use messaging you havee to ensure that the Messenger.Unregister method is called. In other words, when you call Register to handle a messsage make sure you call Unregister as well!

    So in your view you have to register for the Unloaded event; there you then call Messenger.Unregiser(this); where this is your view.

    In ViewModels you have to make sure that the Cleanup method is called to deregister the ViewModel as a message recipient.

    Also see:

    MVVM Light Listener not releasing / deterministic finalization for registered object? and MVVM Light Messenger executing multiple times.

    Laurent is aware of this Problem but - as of now - has no solution.