【问题标题】:Unable to enter "." in a text box with decimal binding无法输入“。”在具有十进制绑定的文本框中
【发布时间】: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


【解决方案1】:

这太烦人了。你不能按“。”但如果你移回一个角色,它会让你。因为“21”。不是有效的小数。

对我来说,我最终放弃了并将该字段设为字符串。必须有更好的方法,但它让我解决了我的用例的问题。然后您还需要检查以确保它是一个数字等,但至少用户体验是他们所期望的。

【讨论】:

    【解决方案2】:

    尝试像这样(仅)处理PreviewTextInput 事件:

    <TextBox x:Name="ValueTextBox" Grid.Column="0" Grid.RowSpan="2" VerticalContentAlignment="Center"
        Text ="{Binding Value}" PreviewTextInput="ValueTextBox_PreviewTextInput" />
    

    private void ValueTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        decimal value;
        e.Handled = string.IsNullOrEmpty(e.Text) || !decimal.TryParse($"{ValueTextBox.Text}{e.Text}",
            System.Globalization.NumberStyles.Any,
            System.Globalization.CultureInfo.InvariantCulture, out value);
    }
    

    【讨论】:

    • 是的。至少在 TextBox 中只接受十进制值时。
    【解决方案3】:

    试试这个

    这将只允许在文本框中输入小数,而不能输入其他任何内容。

    视图模型如下所示:

    private string _decimalVal = "0";
    public string decimalVal
    {
        get { return _decimalVal.ToString(); }
        set
            {
                if (string.IsNullOrEmpty(value) || value == "-")
                    SetProperty(ref _decimalVal, value);
                else if (Decimal.TryParse(value, out decimal newVal))
                {
                    if (newVal == 0)
                        value = "0";
    
                    SetProperty(ref _decimalVal, value = (value.Contains(".")) ? Convert.ToDecimal(value).ToString("0.00") : value);
                }
            }
    }
    

    XAML 用法如下所示:

    <TextBox Text="{Binding decimalVal,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多