Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove input binding added through CommandManager.RegisterClassInputBinding?

I used CommandManager.RegisterClassInputBinding to add binding to the whole type. Now I want to remove it.

This is what I tested.

private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
{
    CommandManager.RegisterClassInputBinding(
        typeof(TextBox),
        new InputBinding(TestCommand, new KeyGesture(Key.S, ModifierKeys.Control)));


    MessageBox.Show("CommandBinding_Executed_1");
}

This method is called on Ctrl+H and registers new input binding for Ctrl+S. If I press Ctrl+S before Ctrl+H it doesn't work, but when I press it after it does.

I checked sender.InputBindings and there was only one binding (Ctrl+S) so I concluded that RegisterClassInputBinding() doesn't add the binding to every existing instance but instead stores bindings associated to the class and then compares them to handled gesture.

But then why there is no RemoveClassInputBinding() method? :(

Edit


I even managed to do what I intended through reflection, but still can't find native method for that, though it would be trivial to implement.

var fieldInfo = typeof(CommandManager).GetField(
    "_classInputBindings", BindingFlags.Static | BindingFlags.NonPublic);
var fieldData = (HybridDictionary)fieldInfo.GetValue(null);
var inputBindingCollection = (InputBindingCollection)fieldData[typeof(TextBox)];
foreach (var o in inputBindingCollection)
{
    if (o == inputBinding)
    {
        MessageBox.Show("half way there");
    }
}
inputBindingCollection.Remove(inputBinding);
like image 443
Sergej Andrejev Avatar asked Jun 15 '09 18:06

Sergej Andrejev


1 Answers

ApplicationCommands.NotACommand was designed for just this purpose:

"This command is always ignored and does not handle the input event that caused it. This provides a way to turn off an input binding built into an existing control."

To use your example:

CommandManager.RegisterClassInputBinding(
    typeof(TextBox),
    new InputBinding(
        ApplicationCommands.NotACommand,
        new KeyGesture(Key.S, ModifierKeys.Control)));
like image 152
user7116 Avatar answered Sep 19 '22 15:09

user7116