WPF: Display a bool value as "Yes" / "No"
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}}" />
Your solution with StringFormat can't work, because it's not a valid format string.
I wrote a markup extension that would do what you want. You can use it like that :
<TextBlock Text="{my:SwitchBinding MyBoolValue, Yes, No}" />
Here the code for the markup extension :
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
}
}
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>
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"/>