Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is StringFormat being ignored in this Xaml? [duplicate]

I have a simple Label that I want to display some diagnostic data with a label "header" built-in. Rather than use 2 labels in a horizontal StackPanel, I figured I'd try using {Binding StringFormat}. Here's the XAML:

   <StackPanel Orientation="Horizontal">
       <Label Content="{Binding Path=SomeData, StringFormat=Value: {0}}" />
   </StackPanel>

In this case SomeData is a string property on the view-model and it is correctly bound to the view. The value of SomeData is "ABC".

I would expect the Label to display: "Value: ABC" It's not. It's displaying simply: "ABC"

What am I doing wrong?

like image 276
Simon Gillbee Avatar asked Dec 06 '25 05:12

Simon Gillbee


2 Answers

Not sure why StringFormat doesn't work, I guess it just doesn't fit property other than Text. For Content property, you can try ContentStringFormat instead :

<Label Content="{Binding Path=SomeData}" ContentStringFormat="Value: {0}" />

Some people suggested to wrap Content with TextBlock and use StringFormat within TextBlock's Text property binding [f.e question 1, question 2].

<Label>
    <TextBlock Text="{Binding Path=SomeData, StringFormat='{}Value: {0}'}"/>
</Label>
like image 119
har07 Avatar answered Dec 07 '25 20:12

har07


StringFormat works on properties of type string (when the object you are binding to is being converted to a string the string format is applied).

The Content property of Label is of type Object.

Suggested solution: Use TextBlock instead!

like image 23
Arcturus Avatar answered Dec 07 '25 22:12

Arcturus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!