WPF: text field and double binding cannot be printed. in topic

I have a text box like

<TextBox Text="{Binding TransactionDetails.TransactionAmount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="5" x:Name="TextBoxAmount"/> 

And I took "TransactionAmount" as Double. It works well on an integer value, but when I type in a floating point value like 100.456, for example, I cannot type '.'

+8
wpf mvvm
source share
5 answers

You update your property every time you change the value. When you enter . , it is written to your view model and updated.

eg. if you type 100. , round to 100 , so you will not see a single dot.

You have the ability to change this behavior:

use delayed binding:

 <TextBox Text="{Binding Path=TransactionDetails.TransactionAmount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Delay=250}" Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="5" x:Name="TextBoxAmount" /> 

change the value only if it differs from the saved one (I would recommend this for each binding):

 private double _transactionAmount; public double TransactionAmount { get { return _transactionAmount; } set { if (_transactionAmount != value) { _transactionAmount = value; Notify("TransactionAmount"); } } 

or use some kind of verification, for example. ValidatesOnExceptions.

+9
source share

The best solution I got using StringFormat as

 <TextBox Text="{Binding TransactionDetails.TransactionAmount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,StringFormat=N2}" Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="5" x:Name="TextBoxAmount" /> 

We can also switch to custom string format as required

+4
source share

Your problem is related to UpdateSourceTrigger. Instead of using there, you can use something like this,

 private double amount; public double Amount { get { return amount; } set { amount= value; PropertyChanged(); Calculation(); } } 

PropertyChanged () You will get this from INotifyPropertyChanged. Click here for more information https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertytyed(v=vs.110).aspx

+1
source share

I give an answer based on Herm's answer above. The explanation is correct, but using " Delay in control" will not solve the problem completely. If the end user enters 0.005, the required delay will be longer, otherwise the value 0 will be overwritten.

Instead, use the string property to bind and try to parse it to double, and based on the results of the analysis, set the long value that you need. Put all the necessary checks before setting the value.

 private double _amount; private string _amountString; public string Amount { get { return _amountString;} set { double d=0; if(Double.TryParse(value, out d)) { _amountString=value; _amount=d; } } } } 
0
source share

In the property binding, use UpdateSourceTrigger=LostFocus . It will update the property when the text field is out of focus.

0
source share

All Articles