Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have assigned a viewmodel as datacontext for a window. When user closes the window using close button in the toolbar, I want it to trigger an ICommand and it's associated function. Need some suggestions about this??

I would appreciate any form of suggestion or help. Thanks

What I have tried:

I could have changed the state of windowstate to none and created custom toolbar, but then the user wont be able to drag the window.
Posted
Updated 8-Jan-19 3:38am

1 solution

I usually Hook the Closing event in the Window code-behind and then, with a dedicated Interface, access the ViewModel from the DataContext... Something like:
C#
public partial class MainWindow
{
    public MainWindow() => Closing += OnClosing;

    private void OnClosing(object sender, CancelEventArgs e)
        => e.Cancel = ((IOnClosing)DataContext).Closing();

There's only a couple of lines of code. (Yes, cast checking not included for this example)

But if you're looking for a cleaner solution to work with a command, here is one: Behavior to support Window Closing in WPF[^]

Both solutions are valid.
 
Share this answer
 
v2
Comments
Rosh@n 9-Jan-19 7:24am    
thanks for your suggestion.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900