Binding double to StringFormat in a TextBox

I am using WPF TextBox bound to the Text property in double on my ViewModel.

My XAML looks like this:

<TextBox Text="{Binding Path=MyDoubleValue, StringFormat=N2, UpdateSourceTrigger=PropertyChanged}" /> 

Unfortunately, when I switch UpdateSourceTrigger to PropertyChanged and enter the value 12345 , I get 12,354.00 ( EDIT : note 5 before 4). This is the result of keeping the cursor in the same place after adding , between 2 and 3 .NET format.

How can I use StringFormat with UpdateSourceTrigger set to PropertyChanged?

Note. This only happens in .NET 4.

+6
Nov 18 2018-11-11T00:
source share
1 answer

Normally, you do not want the UpdateSourceTrigger be PropertyChanged in the TextBox.Text binding, as this triggers a check and change notification every time a key is pressed.

If you do this only so that if the user presses Enter, he saves the value before processing the save command, then I suggest connecting to the PreviewKeyDown event and manually updating the source if the Enter key is pressed (I usually do this AttachedProperty)

 private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { var obj = sender as UIElement; BindingExpression textBinding = BindingOperations.GetBindingExpression( obj, TextBox.TextProperty); if (textBinding != null) textBinding.UpdateSource(); } } 

But with that being said, if you still wanted to use UpdateSourceTrigger=PropertyChanged , consider using formatting when displaying a value, but delete it while the user edits it.

 <TextBox> <TextBox.Style> <Style TargetType="{x:Type TextBox}"> <Setter Property="Text" Value="{Binding Path=MyDoubleValue, StringFormat=N2}" /> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Text" Value="{Binding Path=MyDoubleValue, UpdateSourceTrigger=PropertyChanged}" /> </Trigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> 
+8
Nov 18 '11 at 16:32
source share



All Articles