问题描述
我正在使用以下代码掩盖货币输入字段。唯一的问题是我想将输入限制为2个小数位。如何修改代码以实现此目的?
public class CurrencyConverter : IValueConverter
{
public object Convert(object value,Type targettype,object parameter,CultureInfo culture)
{
return Decimal.Parse(value.ToString()).ToString("C");
}
public object ConvertBack(object value,CultureInfo culture)
{
string valueFromString = Regex.Replace(value.ToString(),@"\D","");
if (valueFromString.Length <= 0)
return 0m;
long valueLong;
if (!long.TryParse(valueFromString,out valueLong))
return 0m;
if (valueLong <= 0)
return 0m;
return valueLong / 100m;
}
}
解决方法
如果要限制两位小数,可以将条件添加到条目textchanged事件中。
喜欢:
<Entry x:Name="entry" Keyboard="Numeric" HorizontalOptions="StartAndExpand" WidthRequest="600" TextChanged="Entry_TextChanged"></Entry>
在后面的代码中:
private void Entry_TextChanged(object sender,TextChangedEventArgs e)
{
if (e.NewTextValue.Contains("."))
{
if (e.NewTextValue.Length - 1 - e.NewTextValue.IndexOf(".") > 2)
{
var s = e.NewTextValue.Substring(0,e.NewTextValue.IndexOf(".") + 2 + 1);
entry.Text =s;
entry.SelectionLength = s.Length;
}
}
}
效果: