'WPF: Display a bool value as "Yes" / "No"

I have a bool value that I need to display as "Yes" or "No" in a TextBlock. I am trying to do this with a StringFormat, but my StringFormat is ignored and the TextBlock displays "True" or "False".

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

Is there something wrong with my syntax, or is this type of StringFormat not supported?

I know I can use a ValueConverter to accomplish this, but the StringFormat solution seems more elegant (if it worked).



Solution 1:[1]

You can also use this great value converter

Then you declare in XAML something like this:

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

And you can use it like this:

<TextBlock Text="{Binding Path=MyBoolValue, Converter={StaticResource BooleanToStringConverter}}" />

Solution 2:[2]

Without converter

            <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>

Solution 3:[3]

There is also another really great option. Check this one : Alex141 CalcBinding.

In my DataGrid, I only have :

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

To use it, you only have to add the CalcBinding via Nuget, than in the UserControl/Windows declaration, you add

<Windows XXXXX xmlns:conv="clr-namespace:CalcBinding;assembly=CalcBinding"/>

  

Solution 4:[4]

This is a solution using a Converter and the ConverterParameter which allows you to easily define different strings for different 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;
        }
    }
}

Define the Converter like this:

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

And use it like this:

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

If you need a different separator than ; (for example .), define the Converter like this instead:

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

Solution 5:[5]

This is another alternative simplified converter with "hard-coded" Yes/No values

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

XAML Usage

<DataGridTextColumn Header="Is Listed?" Binding="{Binding Path=IsListed, Mode=TwoWay, Converter={StaticResource YesNoBoolConverter}}" Width="110" IsReadOnly="True" TextElement.FontSize="12" />

Solution 6:[6]

The following worked for me inside a datagridtextcolumn: I added another property to my class that returned a string depending on the value of MyBool. Note that in my case the datagrid was bound to a CollectionViewSource of MyClass objects.

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}">

Solution 7:[7]

More detailed version based on Cedre's answer:

User.cs

namespace DataTriggerDemo.Model
{
    public class User : INotifyPropertyChanged
    {
        private bool isConnected = false;
        public bool IsConnected
        {
            get => isConnected;
            set
            {
                isConnected = value;
                OnPropertyChanged(nameof(IsConnected));
            }
            public event PropertyChangedEventHandler PropertyChanged;
            public void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    }
}

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    private User user;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    user = FindResource("user") as User;
}

private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
    user.IsConnected = !user.IsConnected;
    return;
}

MainWindow.xaml

<Window x:Class="DataTriggerDemo.MainWindow"
        
        xmlns:model="clr-namespace:DataTriggerDemo.Model"
        Title="Data Trigger Demo" Height="100" Width="100" Loaded="Window_Loaded">

    <Window.Resources>
        <model:User x:Key="user"/>
    </Window.Resources>
    <!-- ... -->
    <TextBlock>
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Text" Value="Disconnected" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Source={StaticResource ResourceKey=user}, Path=IsConnected}" Value="True">
                        <Setter Property="Text" Value="Connected" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
    <!-- ... -->
</Window>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Swisstone
Solution 2 Kelly Elton
Solution 3
Solution 4 Tim Pohlmann
Solution 5 Kwex
Solution 6 MGDsoft
Solution 7 DrInk