Home > Mobile >  How to define closing behaviour of an instance of a Window in C#?
How to define closing behaviour of an instance of a Window in C#?

Time:11-03

I have found that one can add Closing property inside Window tag in .xaml file and then define closing behaviour in the c# file.

<Window 
  ...
  Closing="DataWindow_Closing">

Which works fine.

In my case I have an instance of a window that is defined in c# like this:


    public bool ShowDial()
    {
      var window = new Window
      {
        Content = this,
        ResizeMode = ResizeMode.NoResize
      };
      ...
    }

How to define closing behaviour of this window that is instantiated in c# and not in xaml file?

P.S. I have a UserControl defined in .xaml file

CodePudding user response:

Closing is an event: see enter image description here

If you do so, the event handler will be created automatically for you like this:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    throw new System.NotImplementedException();
}

In this handler you can set e.Cancel = true; if you don't want the window to be closed, e.g. when a validation failed and the data could not be saved.

CodePudding user response:

Closing is an event. You need to give it a listener.
An example with using a lambda expression.

    public bool ShowDial()
    {
      var window = new Window
      {
        Content = this,
        ResizeMode = ResizeMode.NoResize
      };
      window.Closing  = (s, e) =>
      {
          // Some Code
      };
      ...
    }
  • Related