41gov
41gov

Reputation: 31

Cannot set Owner property to a Window that has been closed: Exception

I use WPF 4.0 amd MVVM LIght ToolKit, i have following code:

public partial class View1: Window
{
    /// <summary>
    /// Initializes a new instance of the FavoritesView class.
    /// </summary>
    public View1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {    
        Messenger.Default.Register<NotificationMessage>(this,
            (msg) =>
            {
                if (msg.Notification == "OpenDocument")
                {
                    DocumentView view = new DocumentView();
                    view.Owner=this;
                    view.ShowDialog();
                }
            });            
    }
}

When i many times open-close DocumentView window i get exception "Cannot set Owner property to a Window that has been closed". Why? Any ideas?

Upvotes: 3

Views: 4249

Answers (2)

Vikram Bose
Vikram Bose

Reputation: 3365

you need to Unregister from the message on the window closed event. This will make sure that duplicate registration does not happen when a new instance is created.

private void Window_Closed(object sender, RoutedEventArgs e)
{ 
   Messenger.Default.UnRegister<NotificationMessage>(this);
}

Upvotes: 2

zapico
zapico

Reputation: 2396

You could try to unregister from NotificationMessage to avoid future executions.

Messenger.Default.Unregister(this);

Upvotes: 4

Related Questions