我有一个 TextBlock,它的 Text 属性中有 MultiBinding,还有 StringFormat,用于通过一些附加内容连接两个结果。
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}" >
<Binding Path="Version" />
<Binding Path="OldVersion" StringFormat="{}'({0})'" TargetNullValue=""/>
</MultiBinding>
</TextBlock.Text>
第一个 StringFormat 按预期工作,但第二个未应用:它返回不带括号的值。我不需要第一个 StringFormat 中的括号,因为有时第二个值是 Nothing。 提前致谢。
最佳答案
当您使用MultiBinding
( msdn ) 时,内部StringFormat
将被忽略。
When you use a MultiBinding, the StringFormat property applies only when it is set on the MultiBinding. The value of StringFormat that is set on any child Binding objects is ignored. The number of parameters in a composite string format cannot exceed the number of child Binding objects in the MultiBinding.
您可以使用以下代码代替MultiBinding
:
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Version}" />
<TextBlock Text="{Binding OldVersion, StringFormat=({0}), TargetNullValue=''}" />
</StackPanel>
或者您可以为 OldVersion
属性创建包装属性:
public string OldVersionEx
{
get
{
if (string.IsNullOrEmpty(OldVersion))
return null;
else
return "(" + OldVersion + ")";
}
}
本例中的绑定(bind)如下:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}" >
<Binding Path="Version" />
<Binding Path="OldVersionEx"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
关于wpf StringFormat 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15529986/