我编写了一个简单的WPF自定义文本框控件,用于保存十进制值。以下是其代码的“轻量”版本,省略了大部分方法和属性(但应该足够进行测试):
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace CustomControls
{
public class NumericBox : TextBox
{
public static readonly DependencyProperty ValueProperty;
public static readonly DependencyProperty DecimalCountProperty;
static NumericBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericBox), new FrameworkPropertyMetadata(typeof(NumericBox)));
ValueProperty = DependencyProperty.Register("Value", typeof (decimal?), typeof (NumericBox),
new FrameworkPropertyMetadata(0m, OnValueChanged));
DecimalCountProperty = DependencyProperty.Register("DecimalCount", typeof(int), typeof(NumericBox),
new FrameworkPropertyMetadata(2, OnDecimalCountChanged));
}
public int DecimalCount
{
get { return (int)GetValue(DecimalCountProperty); }
set { SetValue(DecimalCountProperty, value); }
}
public decimal? Value
{
get { return (decimal?)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
}
private static void OnDecimalCountChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
BindingOperations.ClearAllBindings(this);
var textBinding = new Binding("Value")
{
Converter = new TextToNumericBoxValueConverter(),
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
RelativeSource = new RelativeSource(RelativeSourceMode.Self),
ConverterParameter = DecimalCount
};
SetBinding(TextProperty, textBinding);
}
}
public class TextToNumericBoxValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var d = value as decimal?;
if (d == null) return "";
var p = parameter is int ? (int)parameter : 0;
var nf = culture.NumberFormat.Clone() as NumberFormatInfo;
if (nf == null) return "";
nf.NumberDecimalDigits = p;
return d.Value.ToString("N", nf);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
decimal d;
var s = value as string;
if (s == null)
return null;
if (decimal.TryParse(s, out d))
return d;
return null;
}
}
}
现在开始出现奇怪的问题。如果我连续输入几个相同的数字,一切都很正常,直到第十个数字被输入。然后插入符号跳到第五个位置。这是在两位小数的情况下。如果是三位小数,则在第11次按键后插入符号跳到第六个位置。 如果我输入不同的数字,则插入符号会跳到文本末尾。 如果格式中没有小数位数,则一切正常。 我已经尝试手动设置格式,但没有成功。 这里是一个小示例: