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

后端 未结 7 1931
盖世英雄少女心
盖世英雄少女心 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条回答
  •  猫巷女王i
    2020-11-30 01:02

    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

    
    

提交回复
热议问题