解决方法:
将绑定的值换成一个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;
}
}
}
这样就能输入小数点了。