I have found this link about similar problem, except mine has the added twist of the textbox needing to have a formatted value after focus is lost.
<TextBox Text="{Binding Value}" MaxLength="{Binding MaskLength}"/>
<Button Command="{Binding ExecuteCommand}" IsDefault="True"/>
After the user enters text into the textbox I would like to format it with a user defined mask. For example, if the mask is "00000" the convention would be to right justify and zero fill.
123 => 00123
A01 => 00A01
etc...
The problem that I'm running into is that I should only format the text once, when the user has finished typing. Currently, if the user clicks on the button the value the user entered is pushed to the binding and the command is executed. However, if they press the 'Enter' key the value is not pushed to the binding and the command is still executed.
The only way I've found out how to push the binding when the user presses the enter key is to change the textbox's binding and specify UpdateSourceTrigger=PropertyChanged
. This does not work nicely because I don't actually know when the user has finished entering their text.
The easiest solution would be to add codebehind to set the button's focus when the enter key is pressed, however I would like focus to remain at the text box they are currently on. Does anybody have a way around this, maybe an attached property?
EDIT:
Here is a brief example of how my viewmodel is formatting the inputted value.
public string Value
{
get
{
return mFieldValue;
}
set
{
SetValueAndRaisePropertyChange(
ref mFieldValue,
_ApplyFormat( value ),
() => FieldValue );
}
}
Here is the cleanest code behind hack that I've found. I converted this into an attached property but it still doesn't smell quite right.
private void _HandleTxtKeyDown( object sender, KeyEventArgs e )
{
if( e.Key == Key.Enter )
{
TextBox textBox = (TextBox)sender;
BindingExpression binding = textBox.GetBindingExpression( TextBox.TextProperty );
if( binding != null )
{
binding.UpdateSource();
}
}
}