WPF:将布尔值显示为“是” /“否” [英] WPF: Display a bool value as "Yes" / "No"
问题描述
我有一个bool值,我需要在TextBlock中显示为是或否。我试图用StringFormat这样做,但是我的StringFormat被忽略,TextBlock显示True或False。
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 Text="{Binding Path=MyBoolValue, StringFormat='{}{0:Yes;;No}'}" />
我的语法有什么问题,还是不支持这种类型的StringFormat?
Is there something wrong with my syntax, or is this type of StringFormat not supported?
我知道我可以使用ValueConverter完成此操作,但是StringFormat解决方案似乎更加优雅(如果有效)。
I know I can use a ValueConverter to accomplish this, but the StringFormat solution seems more elegant (if it worked).
推荐答案
您的解决方案与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
}
}
这篇关于WPF:将布尔值显示为“是” /“否”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!