Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...