Command for WPF TextBox that fires up when we hit Enter Key

感情迁移 提交于 2019-11-27 18:15:00

Aryan, not every WPF object supports commanding. So if you wan't to do that you'll need either to call your view model from your code behind (a little coupled) or use some MVVM Messaging implementation to decouple that. See MVVM Light Messaging toolkit for an example. Or simple use triggers like this:

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeDataCommand Command="{Binding MyCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

I've faced with the same problem and found solution here, here is the code sample:

<TextBox>
  <TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=CmdSomething}" Key="Enter" />
  </TextBox.InputBindings>
</TextBox>
Nightmare Games

I like Sarh's answer, but it wouldn't work in my program, unless I changed Enter to Return:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{}" />
   </TextBox.InputBindings>
</TextBox>

You can set true to AcceptReturn property.

 <TextBox AcceptsReturn="True" />
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!