我有一個文本框綁定到一個十進制值(屬性),當我鍵入「3」。它不允許我進入,因爲它將它解析回3,因此我失去了「。」。我嘗試了像Delay/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"/>
請告知我該如何糾正這種... 感謝
感謝,當你說事件(只)..ü意味着擺脫所有的其他事件? ?? – ababeel
是的。至少在文本框中只接受十進制值。 – mm8