Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use StringFormat to add a string to a WPF XAML binding

People also ask

How do I format a string in XAML?

Notice that the formatting string is delimited by single-quote (apostrophe) characters to help the XAML parser avoid treating the curly braces as another XAML markup extension. Otherwise, that string without the single-quote character is the same string you'd use to display a floating-point value in a call to String.

How do I bind a text box in WPF?

One-Way Data Binding First of all, create a new WPF project with the name WPFDataBinding. The following XAML code creates two labels, two textboxes, and one button and initializes them with some properties.

What is OneWayToSource data binding in WPF?

OneWayToSource: The Source property will change if the target property is changed. If the user changes the TextProperty , the UserName property will take up the changed value. This again is of intermediate cost as the binding system watches only Target for changes.

What is two way binding WPF?

Two way binding is used when we want to update some controls property when some other related controls property change and when source property change the actual control also updates its property.


Your first example is effectively what you need:

<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work