如何将一个实现与在WPF绑定控制常数文本混合界值?

举例来说,说我有显示订单形式,我想显示文本,如“订单ID 1234”。

的标签

我试过喜欢的东西:

text="Order ID {Binding ....}"

这是可以实现的,或者我必须做类似的流量控制有一个以上的标签?

有帮助吗?

解决方案

如果您正在使用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]

其他提示

在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>

经常被忽视被简单地链接多个一起的TextBlocks例如

<TextBlock Text="{Binding FirstName}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding LastName}" />

另一种方法是使用在其内具有多个运行元件的单一的TextBlock:

<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不是必须的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top