WPF Binding - Default value for empty string

后端 未结 4 573
走了就别回头了
走了就别回头了 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:31

    You should create a converter for this, which implements IValueConverter

    public class StringEmptyConverter : IValueConverter {
    
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
          return string.IsNullOrEmpty((string)value) ? parameter : value;
        }
    
    public object ConvertBack(
          object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
          throw new NotSupportedException();
        }
    
    }
    

    Then in xaml you'd just provide the converter to the binding, (xxx just represents your Window / UserControl / Style ... where the binding is)

    
    
    
    
    

提交回复
热议问题