String format using MultiBinding?
Asked Answered
A

1

35

I'm trying to display a string in XAML using Label control. Following is my XAML code :

<Label Height="28" HorizontalAlignment="Left" Margin="233,68,0,0" Name="label13" VerticalAlignment="Top">
    <Label.Content>
        <MultiBinding StringFormat="{}{0} x {1}">
              <Binding Path="Width" />
              <Binding Path="Height" />
        </MultiBinding>
    </Label.Content>

Width and Height are two properties of my class Movie. I want the label to display : "Width x Height" ex. 800 x 640 However the label control remains empty. Any help is appreciated. I WANT TO DO THIS WITHOUT USING A CONVERTER.


I have modified my xaml by using a TextBlock instead of Label. But still it wont populate display the output.

<TextBlock Height="28" HorizontalAlignment="Left" Margin="233,68,0,0" Name="label13" VerticalAlignment="Top">
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0} x {1}">
                        <Binding Path="Width" />
                        <Binding Path="Height" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
Apocrine answered 4/12, 2011 at 18:11 Comment(2)
Did you look at this? https://mcmap.net/q/428650/-binding-stringformatDecosta
have you implement the INotificationChanged interface for your class movie? is your Binding correct? (look at the vs output window)Brig
B
97

you are trying to bind a string to an object. But StringFormat requires its target to be a string type.

try putting a TextBlock in your label content and bind your data to it

<StackPanel>
  <Slider x:Name="sl1" Minimum="10" Maximum="100"/>
  <Slider x:Name="sl2" Minimum="10" Maximum="100"/>
  <Label x:Name="label13" Background="Yellow" Foreground="Black">
    <Label.Content>
        <TextBlock>
          <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} x {1} Test">
              <Binding ElementName="sl1" Path="Value" />
              <Binding ElementName="sl2" Path="Value" />
            </MultiBinding>
          </TextBlock.Text>
        </TextBlock>
    </Label.Content>
  </Label>
</StackPanel>

EDIT your class Movie must implement the INotificationPropertyChanged interface and your two properties must raise the property changed event with their proprty names!

hope this helps

Brig answered 4/12, 2011 at 20:23 Comment(2)
can you elaborate why it works when TextBlock is inside Label and doesn't work otherwise?Discomposure
@Discomposure because the target of the binding is a different type. TextBlock.Text is a string, but Label.Content is an object. The StringFormat property only kicks in for string-typed targets.Mettah

© 2022 - 2024 — McMap. All rights reserved.