Reputation: 338
I've an Entry
where Text
property is binded to a double
in my view model. This binding is a TwoWay
and has a StringFormat
for 2 decimal places.
Here is the code:
<Entry Keyboard="Numeric" Text="{Binding ViewModel.Weight, Mode=TwoWay, StringFormat='{0:F2}'}" />
It looks like if there is no problem at all, but there is one:
When I start typing into this Entry
the cursor moves to the end, so I've to move it back to the position where I want to type.
It's a really nasty behavior. If I remove the StringFormat
everything goes perfect!
Ideas??
Upvotes: 2
Views: 1339
Reputation: 7445
Really nasty behavior... hey wait, what about behaviors!
I tried to implement your case by following the nice guide the good old @AdamPedley left us before he left Xamarin...
https://xamarinhelp.com/masked-entry-in-xamarin-forms/
Nevertheless, i realized that even that nice made behavior presents that nasty behavior.
The only option i see, that could perform well is applying the format after the user left the entry (when the Unfocused
event is fired!)
To do this you have to subscribe to the Unfocused
events:
<Entry x:Name="entry"
Keyboard="Numeric"
Text="{Binding Weight, Mode=TwoWay}"
Unfocused="entry_Unfocused"/>
And then in the code behind
private void entry_Unfocused(object sender, FocusEventArgs e)
{
if (double.TryParse(entry.Text, out double result))
{
entry.Text = String.Format("{0:F2}", Math.Floor(result * 100) / 100);
}
}
NOTE: By default the String.Format rounds the result. Here i used the solution given in a SO thread to avoid that nasty behavior and cut the decimals up to the second place... but you can just do what you want! (I found out that automatically performing that rounding can lead to the issue i describe in another SO thread!)
Upvotes: 1