If you combine both Ben and ausadmin's solutions, you end up with a very MVVM friendly solution:
<TextBox Text="{Binding Txt1, Mode=TwoWay, UpdateSourceTrigger=Explicit}">
<TextBox.InputBindings>
<KeyBinding Gesture="Enter"
Command="{Binding UpdateTextBoxBindingOnEnterCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type TextBox}}}" />
</TextBox.InputBindings>
</TextBox>
...which means you are passing the TextBox
itself as the parameter to the Command
.
This leads to your Command
looking like this (if you're using a DelegateCommand
-style implementation in your VM):
public bool CanExecuteUpdateTextBoxBindingOnEnterCommand(object parameter)
{
return true;
}
public void ExecuteUpdateTextBoxBindingOnEnterCommand(object parameter)
{
TextBox tBox = parameter as TextBox;
if (tBox != null)
{
DependencyProperty prop = TextBox.TextProperty;
BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop);
if (binding != null)
binding.UpdateSource();
}
}
This Command
implementation can be used for any TextBox
and best of all no code in the code-behind though you may want to put this in it's own class so there are no dependencies on System.Windows.Controls
in your VM. It depends on how strict your code guidelines are.