wpf StringFormat 问题

标签 wpf xaml multibinding

我有一个 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/

相关文章:

c# - 如何导航到 WPF 中的上一页但保留数据?

wpf - 用户控件中的用户控件 : cannot locate resource

c# - 如何避免 XamlParseException 关闭整个应用程序

WPF MultiBinding - UnsetValue 问题

wpf多重绑定(bind)到viewmodel?

c# - WPF 无边框窗口调整大小

c# - 如果对象被处理,则阻止 MouseLeave 触发器

windows-phone-7 - 如何在我的 XAML 中使用来自另一个项目的图像?

c# - 从文件夹中的图像列表显示图像 C# UWP

wpf - MultiBinding unsetvalue 的回退值