jason
jason

Reputation: 7164

TextEdit_KeyDown Event binding to a command

I have a TextEdit and a Button like this :

<dxe:TextEdit Text="{Binding SearchText}" Width="200" Height="25" VerticalAlignment="Center"  KeyDown="TextEdit_KeyDown" />
<Button Command="{Binding SearchCommand}" VerticalAlignment="Center" Margin="20,0,0,0" >

When user clicks the button, SearchCommand works successfully and returns resulsts. I want same thing to happen when user pressses Enter. How can I bind TextEdit_KeyDown event to a command so that I get the same result.

Upvotes: 1

Views: 1252

Answers (2)

DmitryG
DmitryG

Reputation: 17850

Take a look at the EventToCommand behavior from DevExpress MVVM Framework:

View:

<UserControl ...
    DataContext="{dxmvvm:ViewModelSource Type=local:SearchViewModel}"> 
    //...
    <dxe:TextEdit Text="{Binding SearchText}" Width="200" Height="25" VerticalAlignment="Center"> 
        <dxmvvm:Interaction.Behaviors> 
            <dxmvvm:EventToCommand EventName="KeyDown" 
                Command="{Binding SearchByKeyCommand}" 
                PassEventArgsToCommand="True"
            > 
        </dxmvvm:Interaction.Behaviors> 
    </dxe:TextEdit>
    <Button Command="{Binding SearchCommand}" VerticalAlignment="Center" Margin="20,0,0,0" >
    //...

ViewModel:

[POCOViewModel]
public class SearchViewModel {
    public virtual SearchText { 
       get ; 
       set; 
    }
    public void Search() {
        //...  
    }
    public void SearchByKey(KeyEventArgs) {
        Search();  
    }
    public bool CanSearchByKey(KeyEventArgs args) {
        return (args.KeyCode == Keys.Enter) && !string.IsNullOrEmpty(SearchText);
    }
}

Upvotes: 2

Klyse
Klyse

Reputation: 69

 if (e.KeyCode == Keys.Enter)
    {
        //Do your stuff

    }

e is the EventArg which is always transmitted when calling so you have to see what is transmitted in the variable

Upvotes: 0

Related Questions