WPF Binding - Default value for empty string

后端 未结 4 571
走了就别回头了
走了就别回头了 2020-11-28 11:19

Is there a standard way to set a default or fallback value for a WPF binding if the bound string is empty?



        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 11:25

    I was under the impression that FallbackValue provides a value when the binding fails and TargetNullValue provides a value when the bound value is null.

    To do what you want you will either need a converter (possibly with a parameter) to convert an empty string to a target value, or put the logic in your view model.

    I would probably go with a converter something like this (not tested).

    public class EmptyStringConverter : MarkupExtension, IValueConverter
    {  
        public object Convert(object value, Type targetType, 
                              object parameter, CultureInfo culture)
        {
            return string.IsNullOrEmpty(value as string) ? parameter : value;
        }
    
        public object ConvertBack(object value, Type targetType, 
                                  object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
    

提交回复
热议问题