仅绑定标签的一部分 [英] Binding only part of a label
本文介绍了仅绑定标签的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 WPF 绑定控件中实现混合绑定值和常量文本?
How would one achieve mixing bound values with constant text in a WPF bound control?
例如,假设我有一个显示订单的表单,我想要一个显示订单 ID 1234"等文本的标签.
For example, say I have a form displaying orders, and I want a label that displays text like "Order ID 1234".
我尝试过以下方法:
text="Order ID {Binding ....}"
这是可以实现的,还是我必须做一些事情,比如在流控制中拥有多个标签?
Is this achievable, or do I have to do something like having more than one label in a flow control?
推荐答案
如果您使用的是 3.5 SP1,则可以在绑定上使用 StringFormat
属性:
If you're using 3.5 SP1, you can use the StringFormat
property on the binding:
<Label Content="{Binding Order.ID, StringFormat=Order ID {0}}"/>
否则,请使用转换器:
<local:StringFormatConverter x:Key="StringFormatter" StringFormat="Order ID {0}" />
<Label Content="{Binding Order.ID, Converter=StringFormatter}"/>
StringFormatConverter
是一个 IValueConverter
:
[ValueConversion(typeof(object), typeof(string))]
public class StringFormatConverter : IValueConverter
{
public string StringFormat { get; set; }
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture) {
if (string.IsNullOrEmpty(StringFormat)) return "";
return string.Format(StringFormat, value);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
这样就行了.
[Edit : 将 Text
属性更改为 Content
]
[Edit : Change the Text
property to Content
]
这篇关于仅绑定标签的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文