here is the pr...">

WPF: binding to values ​​with a null value in validation

consider the following scenario:

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

here is the property Price

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

this method checks my property

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

this method checks my property if it was 0 or less - minus value - now I need to check if it is null or empty, the problem is that Decimal does not accept values ​​with a null value, any workarounds?

early

+3
source share
3 answers

You can use nullable type

Alternatively, if you do not want to modify your model, then instead bind the property to your view model.

, / . , .

, , , .., .

+3

DataAnnotations. ValidationAttributes. IDataErrorInfo fooobar.com/questions/366891/.... , , , ICommand.

+1

I went with devdigital updated solution, another String property

public String PriceString
    {
        get
        {
            return _PriceString;
        }
        set
        {
            Decimal result;




            if (Decimal.TryParse(value, out result))
            {
                _PriceString = value;
                GlassPrice = result;

            }
            else
            {
                GlassPrice = -33322;
                _PriceString = value;
            }
            OnPropertyChanged("PriceString");
        }
    }

I set GlassPrice as -33322 when the textBox is actually empty, I just use this to distinguish between null values ​​from zero or minus values. gloomy, except for -33322.

0
source

All Articles