WPF:将布尔值显示为“是”/“否”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/841808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:24:21  来源:igfitidea点击:

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

wpfdata-bindingxamlformatting

提问by John Myczek

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 中显示为“是”或“否”。我正在尝试使用 StringFormat 来执行此操作,但我的 StringFormat 被忽略并且 TextBlock 显示“True”或“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?

我的语法有问题,还是不支持这种类型的 StringFormat?

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

我知道我可以使用 ValueConverter 来完成此操作,但 StringFormat 解决方案似乎更优雅(如果有效)。

回答by alf

You can also use this great value converter

您也可以使用这个超值转换器

Then you declare in XAML something like this:

然后在 XAML 中声明如下:

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

And you can use it like this:

你可以像这样使用它:

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

回答by Thomas Levesque

Your solution with StringFormat can't work, because it's not a valid format string.

您使用 StringFormat 的解决方案不起作用,因为它不是有效的格式字符串。

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
    }

}

回答by Cedre

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>

回答by Simon

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

还有另一个非常好的选择。检查这个:Alex141 CalcBinding

In my DataGrid, I only have :

在我的 DataGrid 中,我只有:

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

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

要使用它,您只需通过 GitHub 添加 CalcBinding,而不是在 UserControl/Windows 声明中添加

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

回答by Tim Pohlmann

This is a solution using a Converterand the ConverterParameterwhich allows you to easily define different stringsfor different Bindings:

这是一个使用 aConverter和 the的解决方案,ConverterParameter它允许您轻松定义不同strings的不同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="." />

回答by Kwex

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

XAML 用法

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

回答by MGDsoft

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.

以下内容在 datagridtextcolumn 中对我有用:我向我的类添加了另一个属性,该属性根据 MyBool 的值返回一个字符串。请注意,在我的情况下,数据网格绑定到 MyClass 对象的 CollectionViewSource。

C#:

C#:

public class MyClass        
{     
    public bool MyBool {get; set;}   

    public string BoolString    
    {    
        get { return MyBool == true ? "Yes" : "No"; }    
    }    
}           

XAML:

XAML:

<DataGridTextColumn Header="Status" Binding="{Binding BoolString}">