L.E.O
L.E.O

Reputation: 1109

Notifying view-model on window close

Perhaps someone could comment on this. I have a loosely coupled view and view-model. My view-model needs to do some cleanup when the view closes. So I was wondering what would the the best way to notify view-model that its view is about to close?

Upvotes: 0

Views: 306

Answers (1)

Nick Gotch
Nick Gotch

Reputation: 9407

When I ran into this situation I added some x:Code to the XAML. It was the cleanest I could come up with.

<x:Code>
    <![CDATA[
    // Indirectly attach ExitCommand to the Window's close button
    private void Window_Closed(object sender, EventArgs e)
    {
        var vm = this.DataContext as MyViewModel;
        if(vm != null)
            vm.ExitCommand.Execute(this);
    }
    ]]>
</x:Code>

Make sure to include Closed="Window_Closed" in your <Window>.

Upvotes: 1

Related Questions