简体   繁体   中英

How to add additional actions to command

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM