我已经编写了简单的WPF自定义textbox控件来保存十进制值。以下是其代码的一个非常“轻量级”的版本,没有大部分方法和属性(但对于测试来说应该足够了):
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;
}
}
}现在,奇怪的事情开始了。如果我连续输入几个相同的数字,那么在输入第10个数字之前,一切都是正常的。然后插入符号跳到第5个位置。这是在2位小数的情况下。比方说,如果是3位十进制数字,在第11次击键后,插入符号会跳到第6位。如果我键入不同的数字,插入符号会跳到文本的末尾。如果格式中没有小数位,则一切正常。我尝试过手动设置格式,但没有成功。下面是一个小插图:

发布于 2015-01-03 02:54:46
如果要将插入符号移到小数点之前,请尝试执行以下操作:
this.CaretIndex = string.Substring(0, this.Text.IndexOf(".")).Length;this.CaretIndex = string.Substring(0, this.Text.IndexOf(".") - 1).Length;
如果要将插入符号移动到框的开头:
this.CaretIndex = 0;如果要将插入符号移动到框的末尾:
this.CaretIndex = this.Text.Length;https://stackoverflow.com/questions/26866597
复制相似问题