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

前端 未结 5 2087
太阳男子
太阳男子 2020-12-04 17:31

It is very easy to bind Buttons in WPF apps to Commands in a VIEWMODEL class. I\'d like to achieve a similar binding for a TextB

相关标签:
5条回答
  • 2020-12-04 17:44

    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>
    
    0 讨论(0)
  • 2020-12-04 17:51

    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>
    
    0 讨论(0)
  • 2020-12-04 17:54

    You can set true to AcceptReturn property.

     <TextBox AcceptsReturn="True" />
    
    0 讨论(0)
  • 2020-12-04 18:02
    <TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.InputBindings>
            <KeyBinding Command="{Binding AddCommand}" Key="Return" />
        </TextBox.InputBindings>
    </TextBox>
    

    I took answer from here

    0 讨论(0)
  • 2020-12-04 18:05

    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>
    
    0 讨论(0)
提交回复
热议问题