Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the WPF XAML Data Binding equivalent of String.Format?

Or, to be more clear, how can I format a block of text (in my case, to be included within a tooltip) such that some portions of the text come from bound values.

In plain C# I would use:

_toolTip.Text = string.Format("{1:#0}% up, {2:#0}% down",     Environment.NewLine, percentageOne, percentage2); 

However the WPF XAML markup for a Text property seems able to contain only a single binding. The curly braces gave me high hopes, but this isn't possible:

<Element>   <Element.Tooltip>     <!-- This won't compile -->     <TextBlock Text="{Binding Path=PercentageOne}% up, {Binding Path=PercentageTwo}% down"/>   </Element.Tooltip> </Element> 

I read that the Run.Text property is not a dependency property and can therefore not be bound.

Is there a way I can perform this formatting in XAML?

like image 675
Drew Noakes Avatar asked Jan 15 '09 14:01

Drew Noakes


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.

What is data binding in WPF and XAML?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

What is WPF format?

WPF provides an extensible text formatting engine for this purpose. The advanced text formatting features found in WPF consist of a text formatting engine, a text store, text runs, and formatting properties. The text formatting engine, TextFormatter, creates lines of text to be used for presentation.


2 Answers

You can use MultiBinding + StringFormat (requires WPF 3.5 SP1):

<TextBox.Text>     <MultiBinding StringFormat="{}{1:#0}% up, {2:#0}% down">       <Binding Path="PercentageOne" />       <Binding Path="PercentageTwo"/>     </MultiBinding> </TextBox.Text> 

Regarding Run.Text - you can't bind to it but there are some workarounds:

  • http://fortes.com/2007/03/20/bindablerun/
  • http://paulstovell.net/blog/index.php/attached-bindablerun/
like image 63
aku Avatar answered Oct 12 '22 14:10

aku


I would split into multiple textblocks, binding each one with the StringFormat={0:P} in the binding as such:

<TextBox Text="{Binding Something, StringFormat=\{0:P\}}" /> 

See this post for examples:Lester's WPF Blog on StringFormat

Checkout VS2010 - The binding from properties includes formatting in the options.

like image 26
Dave Avatar answered Oct 12 '22 15:10

Dave