使用退格按钮删除小数时,WPF TextBox表现不佳

问题描述 投票:0回答:1

我是WPF的新手,目前正在做一个处理十进制值的会计基础项目。我在使用退格键删除小数值时遇到问题。

起初我只输入了10位数,但是当试图从最后一位数字中删除时,可以说(____。00)我无法删除。它正在删除两个0并再次添加两个0。

仅当我输入超过10位数时才会出现此问题。

图1:https://ibb.co/mghcsn图片2:https://ibb.co/ghr3Xn

//textbox code
<TextBox x:Name="txtTax2Percent" Tag="{x:Static r:Resources.Tax2Percent}" Text="{Binding Path=Tax2Percent, StringFormat=N2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True,ValidatesOnNotifyDataErrors=True}" TabIndex="1" Margin="10" Grid.Row="4" Grid.RowSpan="1" Grid.Column="4" Grid.ColumnSpan="2" PreviewTextInput="NumberValidationTextBox"></TextBox>

//Model with notify property changed
    [Display(Name = "Tax2 Percent")]
    [Range(0.00, 100.00)]
    [DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
    [Required]
    public decimal Tax2Percent
    {
        get { return _tax2percent; }
        set
        {
            _tax2percent = value;
            ValidateProperty(value);
            base.NotifyPropertyChanged(nameof(Tax2Percent));
        }
    }

//Number Validation
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
        e.Handled = regex.IsMatch(e.Text);
    }
c# .net wpf
1个回答
0
投票
Text="{Binding Path=Tax2Percent, StringFormat=N2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged

这里的问题是每次键入一个字符时它会触发set {}和propertychanged,这会导致文本框更新并触发StringFormat = N2,这会导致格式化十进制字符串。

我现在能想到的唯一解决方案是将UpdateSourceTrigger更改为

UpdateSourceTrigger = LostFocus //so that it only trigger the update once the textbox lost focus
//the validation will only trigger once it lost focus, which is better then sudden lag when
//typing due to validation fail.
© www.soinside.com 2019 - 2024. All rights reserved.