Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

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

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 write my own? I'm on a project where it's tremendous overhead to do something simple like this (shared stuff goes into a separate solution, and the rebuild/checkin/merge process is an overgrown mutated behemoth of a process), so I'd prefer if I could just pass a parameter to the existing one than to jump through the hoops just mentioned.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<Blah.Resources>
  <local:BoolToVisibilityConverter
         x:Key="BoolToHiddenConverter"
         TrueValue="Visible" FalseValue="Hidden" />
</Blah.Resources>

Then use it in one or more bindings like this:

<Foo Visibility="{Binding IsItFridayAlready, 
                          Converter={StaticResource BoolToHiddenConverter}}" />

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...