WPF: Display a bool value as “Yes” / “No”

后端 未结 7 1929
盖世英雄少女心
盖世英雄少女心 2020-11-30 00:21

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

7条回答
  •  情话喂你
    2020-11-30 01:01

    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:

    
    

提交回复
热议问题