0

I want to handle Windows event like Closing, SourceInitialized in my viewModel. I don't want to handle them in my code behind. How can I do that?

Thanks in advance.

WAQ
  • 2,556
  • 6
  • 45
  • 86
  • 3
    Use an implementation like MVVM Light's `EventToCommand`, or use a Behavior to capture the events needed and pass an `ICommand` to the behavior. You can then raise the `Command.Execute` inside the behavior when the required event occurs and handle it in the VM after that. – Viv Aug 04 '13 at 09:53
  • Can you please elaborate on this please? – WAQ Aug 04 '13 at 11:01
  • Very similar question here: http://stackoverflow.com/questions/2927153/wpf-handling-events-from-user-control-in-view-model – Will Faithfull Aug 04 '13 at 13:26
  • I always use attached behaviours for that. I also use an abstraction of the various windows functions like close, maximize, and so on so that the vm can be tested with a mock. But overall, the attached behaviour is the way to go. – Gayot Fow Aug 04 '13 at 17:29

1 Answers1

0

Simply use EventToCommand.

ViewModel:

public ICommand WindowClosing

{
    get
    {
        return new RelayCommand<CancelEventArgs>(
            (args) =>{
                });
    }
}

and in XAML:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <command:EventToCommand Command="{Binding WindowClosing}" />
    </i:EventTrigger>
</i:Interaction.Triggers>