0

Is there any way to override X (red cross) button of the application in MVVM way?

I want that button to hide window in tray (i have already configured tray icon), but don't know how to hide window in a proper way.

  • You may customize your window using [`WindowChrome`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.shell.windowchrome?view=netcore-3.1) and bind any command to close button without breaking any MVVM rules – Pavel Anikhouski Jul 23 '20 at 20:10

1 Answers1

0

You need to override the OnClosing() method.

This is my MainWindow code, you can place this wherever your main window is.

protected override void OnClosing(CancelEventArgs e)
{
    e.Cancel = true;
    Hide();
    base.OnClosing(e);
}

The e.Cancel = true is pertinent here, as setting the Cancel to true cancels the close request so the application is not actually closed.

Edit

I just noticed that your post says in MVVM way, by which I assume you mean writing the code in your View Model? If that is the case, MVVM patter does not dictate that you write zero-code in your code-behind. The idea of MVVM is to decouple View, Model, and ViewModel, but you are still permitted to have code like this when necessary. It doesn't break any MVVM rules, so to speak.

Sach
  • 10,091
  • 8
  • 47
  • 84