Close window from ViewModel

05/10/2011

3 comments

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);
}
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

3 comments

  1. Shimmy04/07/2012 ב 02:09

    @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.

    Reply
  2. Meenakshi21/08/2012 ב 13:00

    Thanks..my problem solved with this code :)

    Reply