1

I am inheriting from a window control that already handles the ApplicationCommands.Close command so that it handles closing the window natively.

I would like to add/override the existing functionality, however I cannot seem to figure out how to do this.

Tried:

  • Adding another of the same command to CommandBindings (first declared seems to win)
  • Check if the command is already existing...Cannot seem to find a way to do this
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180

2 Answers2

1

There are a couple of things you can try. If you are just trying to prevent your window from closing, you can override the OnClosing method and set the cancelled flag:

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

If you want to specifically alter the behavior, you can register with preview versions of the command:

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close"
                    PreviewExecuted="CloseCommandHandler"
                    PreviewCanExecute="CanExecuteHandler" />
</Window.CommandBindings>

The preview routed events will happen before the standard events, allowing you to handle the logic before your base class.

Abe Heidebrecht
  • 30,090
  • 7
  • 62
  • 66
  • Yah, I am indeed trying that and figured I might have to go with the Closing event. I can't use preview because of this bug http://stackoverflow.com/questions/2281825/routeduicommand-previewexecuted-bug I feel like this problem could crop up again, so I am going to leave it open in the hopes for an answer to my actual question. Still +1 – Justin Pihony Jun 25 '13 at 20:17
  • That seems like a nasty bug. I just cracked it open in reflector, and in .NET 4.5 at least, unless you set e.Handled = true in the preview event handler, the normal handler will still get called. So, depending on the version of .NET you're on, this may work! – Abe Heidebrecht Jun 26 '13 at 13:43
0

If you want to replace functionality of the global command, you can find the specific command binding, remove it then add your own logic. See below.

    public ChildWindow()
        :base()
    {
        var appCloseCommandBinding =
            CommandBindings.Cast<CommandBinding>().SingleOrDefault(item => item.Command == ApplicationCommands.Close);

        if(appCloseCommandBinding != null)
            CommandBindings.Remove(appCloseCommandBinding);

        CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, YourCommandLogic));
    }

Hope it can help.

Bill Zhang
  • 1,909
  • 13
  • 10