60

I would like to use StringFormat to do someting like this :

<Label x:Name="myLabel">
    <Label.Content>
        <Multibinding StringFormat="{}{0} - {1}">
            <Binding Path="Lib1" />
            <Binding Path="Lib2" />
        </MultiBinding>
    </Label.Content>
</Label>

However, it's doesn't work and I got this error instead :

MultiBinding failed because it has no valid Converter. MultiBindingExpression:target element is 'Label' (Name='myLabel'); target property is 'Content' (type 'Object')

Is there any way to make this code work ?

Filimindji
  • 1,453
  • 1
  • 16
  • 23

3 Answers3

122

You cant bind this because you are trying to bind a string to an object which wont work because StringFormat requires its target to be a string type. You can get around this by either using a TextBlock instead (which has a Text property) or putting the Textblock as the child of the Label:

<Label x:Name="myLabel">
    <Label.Content>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{}{0} - {1}">
                    <Binding Path="Lib1" />
                    <Binding Path="Lib2" />
                 </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Label.Content>
</Label>
Leom Burke
  • 8,143
  • 1
  • 35
  • 30
  • 1
    That's exactly what I was going to say, and this post confirms it too: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c60b90e6-8426-4c2b-a547-eaa92920862f – Tom Dec 09 '10 at 14:30
  • 1
    Thank you, I'll use a TextBlock instead of a Label. the first solution work as well, but I think the second is more elegant. – Filimindji Dec 09 '10 at 16:16
  • 6
    +1 The latter solution also inherits the style of the label, which is a small bonus if you cannot be bothered to style the `TextBlock`. – Adam Houldsworth Jun 22 '12 at 09:57
7

For those wondering you can also leave the <Label.Content> tag from Leom Burke's answer. This saves another two lines of code.

<Label x:Name="myLabel">
    <TextBlock>
        <TextBlock.Text>
           <MultiBinding StringFormat="{}{0} - {1}">
               <Binding Path="Lib1" />
               <Binding Path="Lib2" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</Label>
Martijn
  • 404
  • 7
  • 16
5
<Label>
   <AccessText>
      <MultiBinding StringFormat="{x:Static properties:Resources.MyText}">
         <Binding Path="MyObj.MyProp" Mode="OneTime"/>
      </MultiBinding>
   </AccessText>
</Label>

Where Resources.MyText can hold anything like "Fox jumps over {0}."

RoadVampire
  • 89
  • 2
  • 3