DCSIMG
Close window from ViewModel - Shimmy on .NET

Close window from ViewModel

Although this is somewhat corny, I will dedicate for it a post. Scenario: you want to close a window from the ViewModel, without exposing the Window to it. This can be done in a simple and clean way.
(Some code removed for brevity)

HTH,
Shimmy

XAML:

<Window
  x:Name="this"
  xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  
  xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
  <i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding}" EventName="Closed">
      <ei:CallMethodAction
        TargetObject="{Binding ElementName=this}"
        MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
<Window>

Code (from the ViewModel - DelegateCommand refers to the one of Prism's library, but it's the same idea of RelayCommand etc.):

private ICommand _SaveAndCloseCommand;
public ICommand SaveAndCloseCommand
{
  get
  {
    return _SaveAndCloseCommand ??
      (_SaveAndCloseCommand = new DelegateCommand(SaveAndClose));
  }
}
private void SaveAndClose()
{
  Save();
  Close();
}
 
public event EventHandler Closed;
private void Close()
{
  if (Closed != nullClosed(thisEventArgs.Empty);
}
Published Wednesday, October 05, 2011 3:57 AM by Shimmy

Comments

# re: Close window from ViewModel

Tuesday, July 03, 2012 10:14 PM by Kevin Marois

Why add the complexity of an event. Why not just do this

www.codeproject.com/.../Heres-a-REALLY-Simple-Solution.aspx

# re: Close window from ViewModel

Wednesday, July 04, 2012 2:09 AM by Shimmy

@Kevin, in my code you don't need to hold or get a reference to the window, it's object agnostic, it could be a window just as it could be a page.

The above code is more MVVMish in my taste.

The other should work as well if you feel more convenient with it.

# re: Close window from ViewModel

Tuesday, August 21, 2012 1:00 PM by Meenakshi

Thanks..my problem solved with this code :)

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems