Set value to null in WPF binding

后端 未结 3 633
借酒劲吻你
借酒劲吻你 2020-11-28 21:37

please take a look at the following line


This Price property from above is a Decimal?

3条回答
  •  一个人的身影
    2020-11-28 22:30

    This value converter should do the trick :

    public class StringToNullableDecimalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, 
            CultureInfo culture)
        {
            decimal? d = (decimal?)value;
            if (d.HasValue)
                return d.Value.ToString(culture);
            else
                return String.Empty;
        }
    
        public object ConvertBack(object value, Type targetType, 
            object parameter, CultureInfo culture)
        {
            string s = (string)value;
            if (String.IsNullOrEmpty(s))
                return null;
            else
                return (decimal?)decimal.Parse(s, culture);
        }
    }
    

    Declare an instance of this converter in the ressources :

    
        
    
    

    And use it in your binding :

    
    

    Note that TargetNullValue is not appropriate here : it is used to define which value should be used when the source of the binding is null. Here Price is not the source, it's a property of the source...

提交回复
热议问题