WPF: Textbox and Binding to Double not able to type . on it
You are updating your property every time the value changes. When you type in a .
, it is written into your viewmodel and the view is updated.
e.g. if you type in 100.
it is rounded to 100
, thus you won't see any dot ever.
You have some options to change this behavior:
use a deferred 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" />
only change the value if it is different from the saved one (I'd recommend this for every binding):
private double _transactionAmount;
public double TransactionAmount
{
get { return _transactionAmount; }
set
{
if (_transactionAmount != value)
{
_transactionAmount = value;
Notify("TransactionAmount");
}
}
or use some kind of validation, e.g. ValidatesOnExceptions.
The best solution I got by using StringFormat
like
<TextBox Text="{Binding TransactionDetails.TransactionAmount, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,StringFormat=N2}" Grid.Column="3"
Grid.ColumnSpan="2" Grid.Row="5" x:Name="TextBoxAmount" />
Also we can go for custom string format as per requirements