سؤال

I have a TextBlock with MultiBinding in the Text property, and StringFormat to concatenate the two results with some additions.

<TextBlock.Text>
   <MultiBinding StringFormat="{}{0} {1}" >
      <Binding Path="Version" />
       <Binding Path="OldVersion" StringFormat="{}'({0})'" TargetNullValue=""/>
    </MultiBinding>
</TextBlock.Text>

The first StringFormat works as expected, but the second isn't applied: it returns the value without parentheses. I don't want the parentheses in the first StringFormat, because sometimes the second value is Nothing. Thanks in advance.

هل كانت مفيدة؟

المحلول

Inner StringFormat will be ignored when you use MultiBinding (msdn).

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.

Instead of MultiBinding you can use following code:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Version}" />
    <TextBlock Text="{Binding OldVersion, StringFormat=({0}), TargetNullValue=''}" />
</StackPanel>

Or you can create wrapper property to OldVersion property:

public string OldVersionEx
{
    get
    {
        if (string.IsNullOrEmpty(OldVersion))
            return null;
        else
            return "(" + OldVersion + ")";
    }
}

And binding in this case is following:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0} {1}" >
            <Binding Path="Version" />
            <Binding Path="OldVersionEx"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top