WPF:绑定到不可为空值,同时验证绑定、为空、WPF

2023-09-05 01:36:36 作者:人海孤独症

考虑以下情形:

 <文本框文本={结合价格}/>
 

这里是价格属性

 公共十进制价格
    {
        得到
        {
            返回_price;
        }
        组
        {
            如果(_price!=值)
            {
                _price =价值;
                OnPropertyChanged(价格);
            }
        }
    }
 

此方法检查我的财产

 私人字符串validateGlassPrice()
  {
    如果(GlassPrice&所述; = 0)
     {
     回报价格不能是0,也为负值;
     }
   其他
     {
     返回的String.Empty;
     }
  }
 
WPF使用命令绑定

此方法检查我的财产,如果它是小于或等于0 - 负值 - 现在我需要检查它是否为空或空过​​,问题是,小数将不接受空的值,任何解决方法。

在此先感谢

解决方案

您可以使用的可空类型

另外,如果不希望更改模型,然后绑定到一个属性上您的视图模型来代替。

通常情况下,我在视图模型使用的字符串值,双击/十进制值,并把在视图模型属性的setter验证preFER。如果一个无效的十进制传递,不更新支持字段。

在适当的时候,有效的视图模型的属性值复制到你的模型,例如该模型需要持久等之前,或在屏幕关闭时。

consider the following scenario:

<TextBox Text="{Binding Price}"/>

here is the Price property

public Decimal Price
    {
        get
        {
            return _Price;
        }
        set
        {
            if (_Price != value)
            {
                _Price = value;
                OnPropertyChanged("Price");
            }
        }
    }

this method examines my property

private string validateGlassPrice()  
  {    
    if (GlassPrice <= 0)   
     {       
     return "price can't be 0 nor a minus value "; 
     } 
   else 
     {           
     return String.Empty;    
     }  
  }

this method examines my property if it was 0 or less - a minus value - now I need to examine if it is null or empty too, the problem is that Decimal won't accept nullable values, any workarounds ?

thanks in advance

解决方案

You could use a Nullable Type

Alternatively, if it is undesirable to change your model, then bind to a property on your view model instead.

Typically, I prefer using string values in the view model for double/decimal values, and putting the validation in the view model property's setter. If an invalid decimal is passed, don't update the backing field.

At an appropriate point, copy the valid view model's property value to your model, for example just before the model needs to be persisted etc, or when the screen closes.