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

解决方法:

将绑定的值换成一个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;
        }
    }
}

这样就能输入小数点了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值