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

编程入门 行业动态 更新时间:2024-10-20 03:13:19
本文介绍了WPF:将布尔值显示为“是";/“不"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个布尔值,需要在 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:将布尔值显示为“是";/“不"

本文发布于:2023-11-17 07:09:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔值   WPF   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!