WPF BooleanToVisibilityConverter que se convierte en Oculto en lugar de colapsado cuando false?


¿Hay alguna manera de usar el convertidor BooleanToVisibilityConverter existente de WPF pero tener valores falsos que se conviertan a Ocultos en lugar del Colapsado predeterminado, o simplemente debo escribir el mío propio? Estoy en un proyecto en el que es una sobrecarga tremenda hacer algo simple como esto (las cosas compartidas entran en una solución separada, y el proceso de reconstrucción/comprobación/fusión es un gigante mutado de un proceso), así que preferiría si pudiera pasar un parámetro al existente que saltar a través del aros acaba de mencionar.

Author: Drew Noakes, 2010-06-27

5 answers

Desafortunadamente, solo se convierte a Visible o Colapsado, por lo que tendrás que escribir el tuyo propio. Aquí está el método de conversión según el Reflector:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    bool flag = false;
    if (value is bool)
    {
        flag = (bool)value;
    }
    else if (value is bool?)
    {
        bool? nullable = (bool?)value;
        flag = nullable.HasValue ? nullable.Value : false;
    }
    return (flag ? Visibility.Visible : Visibility.Collapsed);
}
 23
Author: Quartermeister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-09 22:06:29

He encontrado la solución más simple y mejor para ser esta:

[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;
  }
}

Cuando lo use, simplemente configure una versión que haga exactamente lo que necesita en XAML de esta manera:

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

Luego úsalo en uno o más enlaces como este:

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

Esta solución simple aborda las preferencias ocultas/colapsadas, así como la inversión/negación del efecto.

Los USUARIOS DE SILVERLIGHT deben eliminar la declaración [ValueConversion] ya que ese atributo no forma parte del framework de Silverlight. Tampoco es estrictamente necesario en WPF, pero es consistente con los convertidores incorporados.

 102
Author: Drew Noakes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-13 13:42:49

¿No puedes simplemente usar un estilo en lugar de un convertidor? El código sería algo así como:

<Style x:Key="Triggers" TargetType="Button">
    <Style.Triggers>
    <Trigger Property="{Binding ...}" Value="false">
        <Setter Property = "Visibility" Value="Hidden"/>
    </Trigger>
    </Style.Triggers>
</Style>

Tendrá que proporcionar la propiedad vinculante usted mismo para apuntar a su propiedad bool.

 4
Author: cristobalito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-27 16:48:58

Me gusta usar el parámetro para invertir la lógica de visibilidad: Para invertir la lógica en pocas palabras: ConverterParameter = Invertir en su código xaml

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    bool flag = false;
    if (value is bool)
    {
        flag = (bool)value;
    }

    var reverse = parameter as string;
    if(reverse != null && reverse == "Reverse")
        flag != flag;

    return (flag ? Visibility.Visible : Visibility.Collapsed);
}
 4
Author: hkon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-27 17:12:28

Escribí BoolToVisibilityConverte donde se puede pasar estado invisible en el parámetro:

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var boolValue = (bool) value;
            return boolValue ? Visibility.Visible : (parameter ?? Visibility.Hidden);
        }

Así que puedes enlazar así:

Visibility="{Binding SomeBool, Converter={StaticResource ResourceKey=BooleanToVisibilityConverter}, ConverterParameter={x:Static Visibility.Collapsed}}"

Espero que esto ayude:)

 0
Author: Krzysztof Skowronek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-03 12:35:22