【问题标题】:WPF:Unity: Reuse window after it has been closedWPF:Unity:关闭后重用窗口
【发布时间】:2012-05-06 02:48:24
【问题描述】:

在 ShellViewModel 我有下面的命令绑定来打开一个新窗口“远程视图”

public ICommand RemoteViewCommand
{
    get { return new RelayCommand(RemoteViewExecute, CanRemoteViewExecute); }
}

private void RemoteViewExecute()
{
    if (!CanRemoteViewExecute())
    {
        return;
    }


    var shellRemoteView = Application._Container.Resolve<ShellRemoteView>();
    if (_ShellRemoteView.DataContext==null)
        _ShellRemoteView.DataContext = Application._Container.Resolve<ShellRemoteViewModel>();        

    shellRemoteView.Show();
}

在启动时,我已经使用生命周期管理器注册了“ShellRemoteView”和“ShellRemoteViewModel”以获得单例实例。

_Container.RegisterType<ShellRemoteView>(new ContainerControlledLifetimeManager());
_Container.RegisterType<ShellRemoteViewModel>(new ContainerControlledLifetimeManager());

当 shellRemoteView.Show() 执行并关闭表单,然后再次调用 shellRemoteView.Show() 我得到 Invalid Operation exceptionon:Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after一个窗口已关闭。

Unity 中是否有任何变通方法如果窗口实例关闭,则再次获取窗口实例

【问题讨论】:

    标签: wpf mvvm unity-container


    【解决方案1】:

    这一行是你的问题:

    return new RelayCommand(RemoteViewExecute, CanRemoteViewExecute); 
    

    基本上,您每次调用 Get 命令时都会创建一个新视图。解决这个问题的方法是将一个变量放在您的 GET 语句之外,该语句的范围是 ViewModel 级别。让它存储对视图的引用并返回该引用,而不是每次都创建一个新引用。查看Singleton pattern 了解如何最好地做到这一点。

    【讨论】:

    • 你是这个意思吗?私人 ICommand _remoteViewCommand;公共 ICommand RemoteViewCommand { 获取 { 返回 _remoteViewCommand ?? (_remoteViewCommand = new RelayCommand(RemoteViewExecute, CanRemoteViewExecute)); } } } 这没有帮助。我实际上是在寻找一种通过团结来做事的方法。
    • @Andy - 不确定您所说的“通过 Unity”是什么意思(对 Unity 的大部分内容不太熟悉)。这个链接有帮助吗? answers.unity3d.com/questions/20949/…
    • 非常感谢您的帮助。我的意思是团结:stackoverflow.com/questions/608585/…
    【解决方案2】:

    您应该使用LifetimeManager 注册您的视图以仅创建一个实例。看Using Lifetime Managers

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 2012-06-28
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      相关资源
      最近更新 更多