Question

I would like to know if there's a way to pass the pressed key to my actions through CommandParameter. I want to know which key have been pressed before the action gets allowed to execute

Here is my XAML

<i:Interaction.Triggers>
    <i:EventTrigger EventName="KeyDown">
        <i:InvokeCommandAction Command="{Binding Path=ParseCommand}" CommandParameter=""/>
    </i:EventTrigger>
</i:Interaction.Triggers>

My ViewModel

public class MainViewModel : ViewModelBase
{
    public RelayCommand<EventArgs> ParseCommand { get; set; }

    public MainViewModel()
    {
        this.ParseCommand = new RelayCommand<EventArgs>(ParseLineExecute, CanParseLine);
    }

    public bool CanParseLine(EventArgs e)
    {
        return true;
    }

    public void ParseLineExecute(EventArgs e)
    {
        //something to do
    }
}

If this is not possible, what would be the better way ? I dont want to move from MVVM Light if this could be possible

Was it helpful?

Solution

Ok i fixed the problem. What i had to do is to add the following namespace :

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"

and switch from :

<i:EventTrigger EventName="KeyDown">
    <i:InvokeCommandAction Command="{Binding Path=ParseCommand}" CommandParameter=""/>
</i:EventTrigger>

To :

<i:EventTrigger EventName="KeyDown">
    <cmd:EventToCommand Command="{Binding Path=ParseCommand}" PassEventArgsToCommand="True"/>
</i:EventTrigger>

This way, by knowing the specified event (in this case, "KeyDown") PassEventArgsToCommand will pass the right argument to ParseCommand. By casting explicitly the EventArgs to KeyEventArgs i'm able to know what key have been pressed by the user.

Here's my view model :

public class MainViewModel : ViewModelBase
{
    public RelayCommand<EventArgs> ParseCommand { get; set; }

    public MainViewModel()
    {
        this.ParseCommand = new RelayCommand<EventArgs>(ParseLineExecute, CanParseLine);
    }

    public bool CanParseLine(EventArgs e)
    {
        var pressedKey = (e != null) ? (KeyEventArgs)e : null;

        if (pressedKey.Key == Key.Space && pressedKey != null)
        {
            return true;
        }
        else
        {
            return false;
        }       
    }

    public void ParseLineExecute(EventArgs e)
    {
        //parsing code
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top