【发布时间】:2018-10-03 21:04:20
【问题描述】:
我有一个绑定到十进制值(属性)的文本框,当我键入“3”时。它不允许我输入,因为它会将其解析回 3,因此我丢失了“。”。我尝试了延迟/LostFocus 等解决方案,但这对我不起作用,来自WPF validation rule preventing decimal entry in textbox?。
我现在已经编写了一个 IValueConverter 类,但我显然做得不对。代码如下:
[ValueConversion(typeof(decimal), typeof(string))]
public class DecimalToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//return Decimal.Parse(value.ToString());
if (value == null) return Decimal.Zero;
if (!(value is string)) return value;
string s = (string)value;
int dotCount = s.Count(f => f == '.');
Decimal d;
bool parseValid = Decimal.TryParse(s, out d);
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[-+]?([0-9]*?[.])?[0-9]*$");
bool b = regex.IsMatch(s);
if (dotCount == 1 && b)
{
return s;
}
return d;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value != null ? value.ToString() : "";
}
}
XAML
<TextBox x:Name="ValueTextBox" Grid.Column="0" Grid.RowSpan="2" VerticalContentAlignment="Center" Text ="{Binding Value, Converter={StaticResource DecimalToStringConverter}}" PreviewTextInput="ValueTextBox_OnPreviewTextInput" TextWrapping="Wrap" MouseWheel="ValueTextBox_MouseWheel" PreviewKeyDown="ValueTextBox_PreviewKeyDown" PreviewKeyUp="ValueTextBox_PreviewKeyUp" TextChanged="ValueTextBox_TextChanged" BorderThickness="1,1,0,1"/>
请告诉我如何纠正这个问题... 谢谢
【问题讨论】:
-
类似问题有答案here
标签: c# wpf data-binding