Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct syntax for using StringFormat with single binding?

Tags:

binding

xaml

I can get MultiBinding to work with StringFormat:

<TextBlock.Text>
    <MultiBinding StringFormat="{}{0} {1} (hired on {2:MMM dd, yyyy})">
        <Binding Path="FirstName"/>
        <Binding Path="LastName"/>
        <Binding Path="HireDate"/>
    </MultiBinding>
</TextBlock.Text>

But what is the correct syntax for single binding? The following doesn't work (although it seems to be the same syntax as this example):

<TextBlock Text="{Binding Path=HiredDate, StringFormat='{MMM dd, yyyy}'}"/>

ANSWER:

Thanks Matt, what I needed was a combination of your two answers, this works great:

<TextBlock Text="{Binding Path=HiredDate, 
    StringFormat='Hired on {0:MMM dd, yyyy}'}"/>
like image 313
Edward Tanguay Avatar asked Jun 18 '09 11:06

Edward Tanguay


1 Answers

You want to leave the curly braces out of the format string in your example, because you're not using them as a placeholder (like you'd use "{0}" in String.Format()).

So:

<TextBlock Text="{Binding Path=HiredDate, StringFormat='MMM dd, yyyy'}"/>

If you want to reference the placeholder value somewhere inside the string, you can do so by escaping the curly braces with a backslash:

<TextBlock Text="{Binding Path=HiredDate, StringFormat='Hired on \{0\}'}"/>
like image 104
Matt Hamilton Avatar answered Oct 23 '22 22:10

Matt Hamilton