Stefi Pallo
Stefi Pallo

Reputation: 111

WPF StringFormat TextBlock text

I'm trying to format a string in WPF for a text block. I want to obtain something like this in my text block: [name]. I know to bind text block's text to the string property which I want to show but I don't know how to put the brackets. Can you help me? Thanks!

Upvotes: 3

Views: 785

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31616

Put it in the resources as such, and then access the format in the StringFormat attribute of the binding.

<Page.Resources>
    <system:String x:Key="InBracketsFormat">[{0}]</system:String>
</Page.Resources>


<TextBlock
        Text="{Binding MyValue, StringFormat={StaticResource InBracketsFormat}}"/>

This method provides the advantage of reuse as well as being able to have keyword tokens (such as the ' character) within the text for the format.

Upvotes: 2

dkozl
dkozl

Reputation: 33364

You can do it like this

<TextBlock Text="{Binding MyProperty, StringFormat='[{0}]'}"/>

Upvotes: 2

Related Questions