It is very easy to bind Button
s in WPF apps to Command
s in a VIEWMODEL
class. I\'d like to achieve a similar binding for a TextB
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 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" />
<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding AddCommand}" Key="Return" />
</TextBox.InputBindings>
</TextBox>
I took answer from here
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>