WPF BooleanToVisibilityConverter that converts to Hidden instead of Collapsed when false?

后端 未结 6 1956
予麋鹿
予麋鹿 2020-12-12 22:14

Is there a way to use the existing WPF BooleanToVisibilityConverter converter but have False values convert to Hidden instead of the default Collapsed, or should I just writ

6条回答
  •  醉酒成梦
    2020-12-12 22:44

    I've found the simplest and best solution to be this:

    [ValueConversion(typeof(bool), typeof(Visibility))]
    public sealed class BoolToVisibilityConverter : IValueConverter
    {
      public Visibility TrueValue { get; set; }
      public Visibility FalseValue { get; set; }
    
      public BoolToVisibilityConverter()
      {
        // set defaults
        TrueValue = Visibility.Visible;
        FalseValue = Visibility.Collapsed;
      }
    
      public object Convert(object value, Type targetType, 
          object parameter, CultureInfo culture)
      {
        if (!(value is bool))
          return null;
        return (bool)value ? TrueValue : FalseValue;    
      }
    
      public object ConvertBack(object value, Type targetType, 
          object parameter, CultureInfo culture)
      {
        if (Equals(value, TrueValue))
          return true;
        if (Equals(value, FalseValue))
          return false;
        return null;
      }
    }
    

    When using it, just configure a version that does exactly what you need it to in XAML like this:

    
      
    
    

    Then use it in one or more bindings like this:

    
    

    This simple solution addresses hidden/collapsed preferences as well as reversing/negating the effect.

    SILVERLIGHT USERS must drop the [ValueConversion] declaration as that attribute is not part of the Silverlight framework. It's not strictly needed in WPF either, but is consistent with built-in converters.

提交回复
热议问题