WPF:将bool值显示为"是"/"否"

Joh*_*zek 42 data-binding wpf formatting xaml

我有一个bool值,我需要在TextBlock中显示为"是"或"否".我试图用StringFormat做这个,但我的StringFormat被忽略,TextBlock显示"True"或"False".

<TextBlock Text="{Binding Path=MyBoolValue, StringFormat='{}{0:Yes;;No}'}" />
Run Code Online (Sandbox Code Playgroud)

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

我知道我可以使用ValueConverter来实现这一目标,但StringFormat解决方案看起来更优雅(如果有效).

alf*_*alf 58

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

然后你在XAML中声明如下:

<local:BoolToStringConverter x:Key="BooleanToStringConverter" FalseValue="No" TrueValue="Yes" />
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

<TextBlock Text="{Binding Path=MyBoolValue, Converter={StaticResource BooleanToStringConverter}}" />
Run Code Online (Sandbox Code Playgroud)

  • XAML真的非常喜欢它的价值转换器.最简单的任务:300行转换器. (7认同)

Tho*_*que 44

使用StringFormat的解决方案无法正常工作,因为它不是有效的格式字符串.

我写了一个标记扩展,可以做你想要的.你可以像这样使用它:

<TextBlock Text="{my:SwitchBinding MyBoolValue, Yes, No}" />
Run Code Online (Sandbox Code Playgroud)

这里是标记扩展的代码:

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
    }

}
Run Code Online (Sandbox Code Playgroud)


小智 32

没有转换器

            <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>
Run Code Online (Sandbox Code Playgroud)

  • 你不应该同时触发真假,这是不必要的,可能会导致问题。您应该为该属性设置一个默认设置器,并在此实例中设置一个“DataTrigger”。 (2认同)

Sim*_*mon 6

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

在我的 DataGrid 中,我只有:

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

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

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

  
Run Code Online (Sandbox Code Playgroud)


Tim*_*ann 5

这是一个使用 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样定义转换器:

<local:BoolToStringConverter x:Key="BoolToStringConverter" />
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<TextBlock Text="{Binding MyBoolValue, Converter={StaticResource BoolToStringConverter},
                                       ConverterParameter='Yes;No'}" />
Run Code Online (Sandbox Code Playgroud)

;如果您需要与(例如)不同的分隔符.,请像这样定义转换器:

<local:BoolToStringConverter x:Key="BoolToStringConverter" Separator="." />
Run Code Online (Sandbox Code Playgroud)