1

In ShellViewModel I have below command binding to open a new window "Remote View"

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

On startup I have already registered both "ShellRemoteView" and "ShellRemoteViewModel" using lifetime managers to have singleton instance.

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

When shellRemoteView.Show() executed and I close the form, then again on calling shellRemoteView.Show() I'm getting Invalid Operation excepton:Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.

Is there is any work-around in Unity to get window instance again if its closed.

Anees
  • 885
  • 4
  • 13
  • 31

2 Answers2

0

This line is your problem:

return new RelayCommand(RemoteViewExecute, CanRemoteViewExecute); 

Basically you are creating a new view each time you call the Get command. The way to fix this is to put a variable outside your GET statement that is scoped at the ViewModel level. Have it store a reference to the view and return that reference instead of creating a new reference each time. Look at the Singleton pattern for how best to do this.

IAmTimCorey
  • 16,412
  • 5
  • 39
  • 75
  • you mean this? private ICommand _remoteViewCommand; public ICommand RemoteViewCommand { get { return _remoteViewCommand ?? (_remoteViewCommand = new RelayCommand(RemoteViewExecute, CanRemoteViewExecute)); } } } this doesnt help. I was actually looking for a way to do through unity. – Anees Apr 25 '12 at 12:36
  • @Andy - Not sure what you mean by "through Unity" (not really familiar with most of Unity). Does this link help? http://answers.unity3d.com/questions/20949/singleton-implementation.html – IAmTimCorey Apr 25 '12 at 12:45
  • Thanks for that really appreciate your help. Unity I meant : http://stackoverflow.com/questions/608585/can-someone-explain-microsoft-unity – Anees Apr 25 '12 at 13:16
0

You should register your View with LifetimeManager to create only one instance. Look at Using Lifetime Managers.

Zabavsky
  • 13,340
  • 8
  • 54
  • 79