How to get the sender of the InputBinding-Command

David picture David · Dec 24, 2012 · Viewed 12.2k times · Source

I have this xaml code:

<Window.InputBindings>
    <KeyBinding Command="{Binding Path=KeyEnterCommand}" Key="Enter" />
</Window.InputBindings>

and that's the Code in my ViewModel:

    private RelayCommand _keyEnterCommand;

    public ICommand KeyEnterCommand
    {
        get
        {
            if (_keyEnterCommand == null)
            {
                _keyEnterCommand = new RelayCommand(param => ExecuteKeyEnterCommand());
            }

            return _keyEnterCommand;
        }
    }

    public void ExecuteKeyEnterCommand()
    {
        // Do magic
    }

Now is my question, how can i get the sender of this command?

Answer

Pavlo Glazkov picture Pavlo Glazkov · Dec 24, 2012

If by "sender" you mean the element that was focused when the key was pressed, then you can pass the currently focused element as a parameter to the command, like this:

<Window x:Class="MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="root">
    <Window.InputBindings>
        <KeyBinding Command="{Binding Path=KeyEnterCommand}"
                    CommandParameter="{Binding ElementName=root, Path=(FocusManager.FocusedElement)}"
                    Key="Escape" />
    </Window.InputBindings>
...

private RelayCommand<object> _keyEnterCommand;

public ICommand KeyEnterCommand
{
    get
    {
        if (_keyEnterCommand == null)
        {
            _keyEnterCommand = new RelayCommand<object>(ExecuteKeyEnterCommand);
        }

        return _keyEnterCommand;
    }
}

public void ExecuteKeyEnterCommand(object sender)
{
    // Do magic
}