TextBox绑定到double并输入小于-1的负数时的问题

Dav*_*eli 1 c# wpf

我将文本框绑定到Propery并输入小于-1的负数时出现问题 - 例如-0.45:

文本框:

<TextBox Text="{Binding Txt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)

和财产:

  double txt;
    public double Txt
    {
        get { return txt; }
        set { txt = value; OnPropertyChanged("Txt"); }
    }
Run Code Online (Sandbox Code Playgroud)

似乎当我尝试输入-0.54时,它立即变为0,为什么?

Avn*_*esh 5

这是完成工作的转换器(因此保留您的视图模型 - 您可以将它用于十进制和双精度).我们最初需要保持小数和-ve位置:

 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我们持有价值观或对绑定无所作为