且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:将布尔值显示为“是";/“不"

更新时间:2022-05-09 22:22:58

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

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

我写了一个标记扩展来满足你的需求.你可以这样使用它:

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
    }

}