TextBox 绑定到 double 并输入小于 -1 的负数时的问题 [英] An issue when TextBox is binding to double and enter negative number that little than -1
本文介绍了TextBox 绑定到 double 并输入小于 -1 的负数时的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我将文本框绑定到属性并输入小于 -1 的负数时遇到问题 - 例如 -0.45:
I have an issue when i binding a textbox to Propery and enter a negative number that is less than -1 - for example -0.45:
文本框:
<TextBox Text="{Binding Txt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
和财产:
double txt;
public double Txt
{
get { return txt; }
set { txt = value; OnPropertyChanged("Txt"); }
}
似乎当我尝试输入 -0.54 时它会立即更改为 0,为什么?
it seems when i try to enter -0.54 it changes immediatly to 0, why?
推荐答案
这是完成这项工作的转换器(所以保持你的视图模型原样 - 你可以将它用于十进制和双精度).我们只需要最初保留小数点和 -ve 位置:
Here is the convertor that does the job ( So leave your view model as it is- You can use it for both decimal and double). We just need to hold the decimal and -ve position initially:
public class DecimalConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value !=null)
{
return value.ToString();
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string data = value as string;
if (data == null)
{
return value;
}
if (data.Equals(string.Empty))
{
return 0;
}
if (!string.IsNullOrEmpty(data))
{
decimal result;
//Hold the value if ending with .
if (data.EndsWith(".") || data.Equals("-0"))
{
return Binding.DoNothing;
}
if (decimal.TryParse(data, out result))
{
return result;
}
}
return Binding.DoNothing;
}
}
所以我们持有值或在绑定时不做任何事情
So we hold the values or do nothing on binding
这篇关于TextBox 绑定到 double 并输入小于 -1 的负数时的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文