无法将Owner属性设置为已关闭的Window:Exception

时间:2011-09-16 11:55:33

标签: wpf mvvm-light

我使用WPF 4.0 amd MVVM LIght ToolKit,我有以下代码:

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();
                }
            });            
    }
}

当我多次打开 - 关闭DocumentView窗口时,我得到异常“无法将所有者属性设置为已关闭的窗口”。为什么?有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您可以尝试从NotificationMessage取消注册以避免将来执行。

Messenger.Default.Unregister(this);

答案 1 :(得分:2)

您需要从窗口关闭事件的消息中取消注册。 这将确保在创建新实例时不会发生重复注册。

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