简体   繁体   English

Xamarin Forms:双向绑定和字符串格式的问题

[英]Xamarin Forms: Problem with TwoWay Binding and StringFormat

I've an Entry where Text property is binded to a double in my view model.我有一个Entry ,其中Text属性在我的视图 model 中绑定到double精度。 This binding is a TwoWay and has a StringFormat for 2 decimal places.此绑定是TwoWay并且有 2 个小数位的StringFormat

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.当我开始在此条目中Entry时,cursor 移动到最后,所以我必须将它移回我想要输入的 position。

It's a really nasty behavior.这是一个非常讨厌的行为。 If I remove the StringFormat everything goes perfect!如果我删除StringFormat一切都会完美!

Ideas??想法??

在此处输入图像描述

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...我试图通过遵循良好的指导来实现你的案例,好老的@AdamPedley 在他离开 Xamarin 之前离开了我们......

https://xamarinhelp.com/masked-entry-in-xamarin-forms/ 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!)我看到的唯一可以执行良好的选项是在用户离开条目后应用格式(当触发Unfocused事件时!)

To do this you have to subscribe to the Unfocused events:为此,您必须订阅Unfocused事件:

<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.注意:默认情况下,String.Format 会舍入结果。 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!在这里,我使用了 SO 线程中给出的解决方案来避免这种讨厌的行为,并将小数位减少到第二位......但你可以做你想做的事! (I found out that automatically performing that rounding can lead to the issue i describe in another SO thread !) (我发现自动执行舍入会导致我在另一个 SO 线程中描述的问题!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM