WPF: Muestra un valor bool como " Yes " / " No"


Tengo un valor bool que necesito mostrar como "Yes" o "No" en un TextBlock. Estoy tratando de hacer esto con un StringFormat, pero mi StringFormat es ignorado y el TextBlock muestra " True "o"False".

<TextBlock Text="{Binding Path=MyBoolValue, StringFormat='{}{0:Yes;;No}'}" />

¿hay algo malo con mi sintaxis, o este tipo de StringFormat no se admite?

Sé que puedo usar un ValueConverter para lograr esto, pero la solución StringFormat parece más elegante (si funcionó).

Author: John Myczek, 2009-05-09

7 answers

Su solución con StringFormat no puede funcionar, porque no es una cadena de formato válida.

Escribí una extensión de marcado que haría lo que quieres. Puedes usarlo así :

<TextBlock Text="{my:SwitchBinding MyBoolValue, Yes, No}" />

Aquí el código para la extensión de marcado :

public class SwitchBindingExtension : Binding
{
    public SwitchBindingExtension()
    {
        Initialize();
    }

    public SwitchBindingExtension(string path)
        : base(path)
    {
        Initialize();
    }

    public SwitchBindingExtension(string path, object valueIfTrue, object valueIfFalse)
        : base(path)
    {
        Initialize();
        this.ValueIfTrue = valueIfTrue;
        this.ValueIfFalse = valueIfFalse;
    }

    private void Initialize()
    {
        this.ValueIfTrue = Binding.DoNothing;
        this.ValueIfFalse = Binding.DoNothing;
        this.Converter = new SwitchConverter(this);
    }

    [ConstructorArgument("valueIfTrue")]
    public object ValueIfTrue { get; set; }

    [ConstructorArgument("valueIfFalse")]
    public object ValueIfFalse { get; set; }

    private class SwitchConverter : IValueConverter
    {
        public SwitchConverter(SwitchBindingExtension switchExtension)
        {
            _switch = switchExtension;
        }

        private SwitchBindingExtension _switch;

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                bool b = System.Convert.ToBoolean(value);
                return b ? _switch.ValueIfTrue : _switch.ValueIfFalse;
            }
            catch
            {
                return DependencyProperty.UnsetValue;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return Binding.DoNothing;
        }

        #endregion
    }

}
 41
Author: Thomas Levesque,
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
2009-05-08 21:28:18

También puede usar este gran convertidor de valor

Entonces declaras en XAML algo como esto:

<local:BoolToStringConverter x:Key="BooleanToStringConverter" FalseValue="No" TrueValue="Yes" />

Y puedes usarlo así:

<TextBlock Text="{Binding Path=MyBoolValue, Converter={StaticResource BooleanToStringConverter}}" />
 56
Author: alf,
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-11-07 11:17:30

Sin convertidor

            <TextBlock.Style>
                <Style TargetType="{x:Type TextBlock}">
                    <Setter Property="Text" Value="OFF" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding MyBoolValue}" Value="True">
                            <Setter Property="Text" Value="ON" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
 29
Author: Cedre,
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-01 22:24:57

También hay otra opción realmente genial. Marque esta: Alex141 CalcBinding .

En mi DataGrid, solo tengo :

<DataGridTextColumn Header="Mobile?" Binding="{conv:Binding (IsMobile?\'Yes\':\'No\')}" />

Para usarlo, solo tienes que agregar el CalcBinding a través de GitHub, que en la declaración UserControl/Windows, agregas

<Windows XXXXX xmlns:conv="clr-namespace:CalcBinding;assembly=CalcBinding"/>
 3
Author: Simon,
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
2015-10-08 17:42:15

Esta es una solución que utiliza un Converter y el ConverterParameter que le permite definir fácilmente diferente strings para diferente Bindings:

public class BoolToStringConverter : IValueConverter
{
    public char Separator { get; set; } = ';';

    public object Convert(object value, Type targetType, object parameter,
                          CultureInfo culture)
    {
        var strings = ((string)parameter).Split(Separator);
        var trueString = strings[0];
        var falseString = strings[1];

        var boolValue = (bool)value;
        if (boolValue == true)
        {
            return trueString;
        }
        else
        {
            return falseString;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              CultureInfo culture)
    {
        var strings = ((string)parameter).Split(Separator);
        var trueString = strings[0];
        var falseString = strings[1];

        var stringValue = (string)value;
        if (stringValue == trueString)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Defina el convertidor de la siguiente manera:

<local:BoolToStringConverter x:Key="BoolToStringConverter" />

Y úsalo así:

<TextBlock Text="{Binding MyBoolValue, Converter={StaticResource BoolToStringConverter},
                                       ConverterParameter='Yes;No'}" />

Si necesita un separador diferente a ; (por ejemplo .), defina el convertidor de la siguiente manera:

<local:BoolToStringConverter x:Key="BoolToStringConverter" Separator="." />
 2
Author: Tim Pohlmann,
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-09-30 07:35:55

Este es otro convertidor simplificado alternativo con valores" hard-coded " Sí/No

[ValueConversion(typeof (bool), typeof (bool))]
public class YesNoBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var boolValue = value is bool && (bool) value;

        return boolValue ? "Yes" : "No";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value != null && value.ToString() == "Yes";
    }
}

Uso de XAML

<DataGridTextColumn Header="Is Listed?" Binding="{Binding Path=IsListed, Mode=TwoWay, Converter={StaticResource YesNoBoolConverter}}" Width="110" IsReadOnly="True" TextElement.FontSize="12" />
 1
Author: Kwex,
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
2015-03-16 12:21:58

Lo siguiente funcionó para mí dentro de una datagridtextcolumn: Agregué otra propiedad a mi clase que devolvía una cadena dependiendo del valor de myBool. Tenga en cuenta que en mi caso la cuadrícula de datos estaba vinculada a un CollectionViewSource de objetos MyClass.

C#:

public class MyClass        
{     
    public bool MyBool {get; set;}   

    public string BoolString    
    {    
        get { return MyBool == true ? "Yes" : "No"; }    
    }    
}           

XAML:

<DataGridTextColumn Header="Status" Binding="{Binding BoolString}">
 0
Author: MGDsoft,
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-05-22 17:05:52