我有一个带有数字键盘的 Xamarin.Forms 条目,它将代表 pt-BR REAL 货币 (999.999,99)。当我在数字键盘中输入数字时,需要在输入时自动添加逗号(代表小数)和点(代表千位)。
为了实现这一目标,Xamarin.Forms 中适用于所有平台的最佳实践/设计模式是什么?
最佳答案
诀窍是使用 TextChanged 事件。第一步,我从字符串中删除了 $,以便我可以解析新的文本值。如果解析失败,则意味着用户添加了非数字字符,我们只需恢复为旧文本即可。
接下来,我们检测用户是否添加了一个新数字及其在小数点右侧的位置(例如 1.532)。如果是这样,我们将小数点向右移动 * 10。对于删除,执行相反的操作。
哦,差点忘了我们什么时候初始化这个数字的!我们输入的第一个数字将是整数,因此我们 * 100 以确保我们输入的第一个数字以分数开头。
一旦我们得到了正确的小数点,我们就使用 num.ToString("C");
来显示它
xaml:
<Entry
Keyboard="Numeric"
TextChanged="OnFinancialTextChanged"
Placeholder="$10.00"
Text="{Binding RetailPrice}"/>
然后在CS
.cs:
private void OnFinancialTextChanged(object sender, TextChangedEventArgs e)
{
var entry = (Entry)sender;
var amt = e.NewTextValue.Replace("$", "");
if (decimal.TryParse(amt, out decimal num))
{
// Init our number
if(string.IsNullOrEmpty(e.OldTextValue))
{
num = num / 100;
}
// Shift decimal to right if added a decimal digit
else if (num.DecimalDigits() > 2 && !e.IsDeletion())
{
num = num * 10;
}
// Shift decimal to left if deleted a decimal digit
else if(num.DecimalDigits() < 2 && e.IsDeletion())
{
num = num / 10;
}
entry.Text = num.ToString("C");
}
else
{
entry.Text = e.OldTextValue;
}
}
我创建了这些扩展方法来帮助逻辑
public static class ExtensionMethods
{
public static int DecimalDigits(this decimal n)
{
return n.ToString(System.Globalization.CultureInfo.InvariantCulture)
.SkipWhile(c => c != '.')
.Skip(1)
.Count();
}
public static bool IsDeletion(this TextChangedEventArgs e)
{
return !string.IsNullOrEmpty(e.OldTextValue) && e.OldTextValue.Length > e.NewTextValue.Length;
}
}
关于带有自动千位和小数分隔符的 Xamarin.Forms 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38770910/