简体   繁体   中英

How to pass KeyEventArgs parameters to the command

Here is my code:

XAML:

<intr:Interaction.Triggers>
    <intr:EventTrigger EventName="KeyDown">
        <intr:InvokeCommandAction Command="{Binding KeyDownEvent}" />
    </intr:EventTrigger>
</intr:Interaction.Triggers>

Code :

public DelegateCommand<KeyEventArgs> KeyDownEvent { get; private set; }

public MainWindowViewModel()
{
        KeyDownEvent = new DelegateCommand<KeyEventArgs>(KeyDownEventHandler);
}

private void KeyDownEventHandler(KeyEventArgs args) //args is always null
{
    try
    {
        if (args.Key == Key.System && args.SystemKey == Key.F4)
        {
            args.Handled = true;
        }
    }
    catch (Exception ex)
    {

    }
}

When press any key the event is fired and the KeyDownEventHandler is invoked, but the args parameter is always null .

You have to set the PassEventArgsToCommand property to True .

<intr:InvokeCommandAction Command="{Binding KeyDownEvent}"
                          PassEventArgsToCommand="True"/>

Be aware, that is the InvokeCommandAction from the Microsoft XAML behaviors NuGet package . This is a replacement of the legacy Blend behaviors ( System.Windows.Interactivity ). The new XML namespace to use after installing the package is http://schemas.microsoft.com/xaml/behaviors . You can specify the property path in the command parameter with EventArgsParameterPath .

Alternatively, the InvokeCommandAction shipped with Prism will pass the event args, too, if you do not set a CommandParameter explicitly. It also allows to specify a property in the command parameter with TriggerParameterPath . For more information refer to the documentation .

[...] the Prism InvokeCommandAction uses the EventArgs parameter passed to it from the parent trigger, passing it to the associated command if the CommandParameter is not set.

The old variant of InvokeCommandAction does not provide an option to pass the event arguments to the command.

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