在我的WPF项目中,我有Label
:
<Label Grid.Column="1"
Grid.Row="1">
<PriorityBinding>
<Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
<Binding Source="Unemployed" />
</PriorityBinding>
</Label>
StringFormat on似乎没有做任何事情。但是,如果我添加这个:
<Label.ContentStringFormat>
Employer: {0}
</Label.ContentStringFormat>
...格式化工作正常,但它会影响两个绑定。如何将StringFormat仅应用于顶部绑定?
更新:如果没有使用TextBlock
代替Label
,有没有办法实现这一目标?
答案 0 :(得分:3)
StringFormat用于字符串(例如TextBlock.Text),但label.Content是对象的类型,您必须使用ContentStringFormat作为Label。
编辑:你的问题 - 如果你可以将标签变为TextBlock,那么你就不再有任何问题了。但如果你想留下标签,我猜你必须使用转换器来应用你的字符串格式。
答案 1 :(得分:1)
如前所述,只有当目标属性类型为文本时,StringFormat才有效。
一种解决方案是使用ValueConverter格式化结果,您可以将格式字符串作为ConverterParameter传递。
无法创建类型为string
的附加DependencyPropertypublic static class Helper {
public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(Helper));
public static string GetText(DependencyObject o) {
return (string)o.GetValue(TextProperty);
}
public static void SetText(DependencyObject o, string value) {
o.SetValue(TextProperty,value);
}
}
然后你可以做
<Label Grid.Column="1"
Grid.Row="1"
Content="{Binding RelativeSource={RelativeSource Self}, Path=(ui:Helper.Text)}">
<ui:Helper.Text>
<PriorityBinding>
<Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
<Binding Source="Unemployed" />
</PriorityBinding>
</ui:Helper.Text>
</Label>
评论中描述的问题可能与This Question有关,因此XAML可能需要看起来像这样。
<Label Grid.Column="1"
Grid.Row="1" >
<Binding RelativeSource="{RelativeSource Self}" Path="(ui:Helper.Text)" />
<ui:Helper.Text>
<PriorityBinding>
<Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
<Binding Source="Unemployed" />
</PriorityBinding>
</ui:Helper.Text>
</Label>
或者从this MSDN question你可以做到
<Label Grid.Column="1"
Grid.Row="1" >
<ui:Helper.Text>
<PriorityBinding>
<Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
<Binding Source="Unemployed" />
</PriorityBinding>
</ui:Helper.Text>
<Label.Content>
<Binding RelativeSource="{RelativeSource Self}" Path="(ui:Helper.Text)" />
</Label.Content>
</Label>
确保将ui的xmlns绑定到Helper类的命名空间
您始终可以将内容相对源绑定放入样式中,以避免为所有标签重复它。