仅绑定标签的一部分

Nei*_*ell 26 wpf binding label

如何在WPF绑定控件中实现将绑定值与常量文本混合?

例如,假设我有一个显示订单的表单,我想要一个显示"订单ID 1234"等文本的标签.

我尝试过这样的事情:

text="Order ID {Binding ....}"
Run Code Online (Sandbox Code Playgroud)

这是可以实现的,还是我必须做一些事情,比如在流量控制中有多个标签?

LPC*_*Roy 51

Binding.StringFormat属性不适用于标签,您需要在Label上使用ContentStringFormat属性.
例如,以下示例将起作用:

<Label>
    <Label.Content>
        <Binding Path="QuestionnaireName"/>
    </Label.Content>
    <Label.ContentStringFormat>
        Thank you for taking the {0} questionnaire
    </Label.ContentStringFormat>
</Label> 
Run Code Online (Sandbox Code Playgroud)

虽然这个样本不会:

<Label Content="{Binding QuestionnaireName}" ContentStringFormat="Thank you for taking the {0} questionnaire" />
Run Code Online (Sandbox Code Playgroud)

  • 由于`Label.Content`是`Object`类型,绑定看不需要将值转换并格式化为字符串. (2认同)

Inf*_*ris 23

如果您使用的是3.5 SP1,则可以StringFormat在绑定上使用该属性:

<Label Content="{Binding Order.ID, StringFormat=Order ID \{0\}}"/>
Run Code Online (Sandbox Code Playgroud)

否则,请使用转换器:

<local:StringFormatConverter x:Key="StringFormatter" StringFormat="Order ID {0}" />
<Label Content="{Binding Order.ID, Converter=StringFormatter}"/>
Run Code Online (Sandbox Code Playgroud)

随着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();
    }
Run Code Online (Sandbox Code Playgroud)

那就行了.

[ 编辑:将Text属性更改为Content]

  • AFAIK标签控件没有`Text`属性.你应该绑定到`Content`属性 (3认同)

ben*_*wey 5

例如,经常被忽视的只是简单地将多个文本块链接在一起

<TextBlock Text="{Binding FirstName}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding LastName}" />
Run Code Online (Sandbox Code Playgroud)

  • 这取决于它所处的堆叠面板类型 (4认同)