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
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:
And use it like this:
If you need a different separator than ; (for example .), define the Converter like this instead: