如何在 WPF 绑定控件中实现绑定值与常量文本的混合?
例如,假设我有一个显示订单的表单,并且我想要一个显示诸如“订单 ID 1234”之类的文本的标签。
我试过这样的事情:
text="Order ID {Binding ....}"
这是可以实现的,还是我必须做一些事情,比如在流控制中有多个标签?
Binding.StringFormat 属性对标签不起作用,您需要在标签上使用 ContentStringFormat 属性。
例如,以下示例将起作用:
<Label>
<Label.Content>
<Binding Path="QuestionnaireName"/>
</Label.Content>
<Label.ContentStringFormat>
Thank you for taking the {0} questionnaire
</Label.ContentStringFormat>
</Label>
与短版相同:
<Label Content="{Binding QuestionnaireName}" ContentStringFormat="Thank you for taking the {0} questionnaire" />
使用它在值之后显示一个单位:
<Label Content="{Binding Temperature}" ContentStringFormat="{}{0}°C" />
虽然此示例不会:
<Label>
<Label.Content>
<Binding Path="QuestionnaireName" StringFormat="Thank you for taking the {0} questionnaire"/>
</Label.Content>
</Label>
如果您使用的是 3.5 SP1,则可以StringFormat
在绑定上使用该属性:
<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();
}
这样就行了。
[编辑:将Text
属性更改为Content
]
例如,经常被忽视的是简单地将多个文本块链接在一起
<TextBlock Text="{Binding FirstName}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding LastName}" />
另一种方法是使用单个 TextBlock,其中包含多个 Run 元素:
<TextBlock><Run>Hello</Run><Run>World</Run></TextBlock>
..但是要绑定到您需要使用的元素,请添加一个BindableRun类。
更新但是这种技术有一些缺点......见这里
我找到了另一种方法。@Inferis 的解决方案对我不起作用,@LPCRoy 的解决方案对我来说并不优雅:
<Label Content="{Binding Path=Order.ID, FallbackValue=Placeholder}" ContentStringFormat="Order ID {0}">
这是我目前最喜欢的,它看起来灵活而浓缩。
修改了 Mikolaj 的答案。
<Label Content="{Binding Order.ID}" ContentStringFormat="Order ID {0}" />
FallbackValue 不是必须的。