WPF输入框双向绑定Decimal类等数据无法输入小数点

这篇博客介绍了如何在WPF应用程序中,通过数据绑定和属性更改事件处理,确保TextBox控件能正确输入并格式化小数值。当用户在TextBox中输入小数时,系统会自动尝试将输入的字符串转换为decimal类型,并在格式错误时弹出提示。同时,代码展示了如何在XAML和后台类文件中设置和更新折扣值的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决方法:

将绑定的值换成一个string类型的参数

xaml文件

<StackPanel Orientation="Horizontal">
	<TextBlock Text="*" FontSize="14" Foreground="Red" Margin="30 0 -40 0" VerticalAlignment="Top"/>
    <Label Content="折      扣:" Style="{StaticResource RightContentLabel}"/>
    <TextBox Width="250"  Text="{Binding DiscountExample.DiscountStr,UpdateSourceTrigger=PropertyChanged}" />
    <Label Content=" 折扣大小范围0-1,例如:0.8" Width="250" Style="{StaticResource LeftContentLabel}"></Label>
</StackPanel>

类文件

[JsonProperty(PropertyName = "discount")]
public decimal? Discount
{
    get
    {
        return discount;
    }
    set
    {
        discount = value;
        if (string.IsNullOrWhiteSpace(discountStr) && !string.IsNullOrWhiteSpace(discount.ToString()))
        {
            discountStr = discount.ToString();//初始化显示
        }
        OnPropertyChanged("Discount");
    }
}


[JsonIgnore]
public string DiscountStr
{
    get
    {
        return discountStr;
    }
    set
    {
        discountStr = value;
        OnPropertyChanged("DiscountStr");
    }
}

ViewMode设置值一起发生改变,使用try,catch判断格式是否正确

public ViewModel()
{
	DiscountExample.PropertyChanged += Discount_PropertyChanged;
}

private void Discount_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "DiscountStr" && !string.IsNullOrWhiteSpace(discountExample.DiscountStr) && !discountExample.DiscountStr.Equals(discountExample.Discount)) {
        try
        {
            discountExample.Discount = Convert.ToDecimal(DiscountExample.DiscountStr);
        }
        catch
        {
            SystemService.MsgBoxService.ShowMsgBox("输入格式错误!");
            return;
        }
    }
}

这样就能输入小数点了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值