什么是String.Format的WPF XAML数据绑定等价物?

Dre*_*kes 31 .net wpf formatting binding text-formatting

或者,更清楚的是,如何格式化文本块(在我的情况下,包含在工具提示中),使得文本的某些部分来自绑定值.

在普通的C#中我会使用:

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

但是,Text属性的WPF XAML标记似乎只能包含一个绑定.花括号给了我很大的希望,但这是不可能的:

<Element>
  <Element.Tooltip>
    <!-- This won't compile -->
    <TextBlock Text="{Binding Path=PercentageOne}% up, {Binding Path=PercentageTwo}% down"/>
  </Element.Tooltip>
</Element>
Run Code Online (Sandbox Code Playgroud)

我读到该Run.Text属性不是依赖属性,因此不能绑定.

有没有办法在XAML中执行此格式化?

aku*_*aku 45

您可以使用MultiBinding + StringFormat(需要WPF 3.5 SP1):

<TextBox.Text>
    <MultiBinding StringFormat="{}{1:#0}% up, {2:#0}% down">
      <Binding Path="PercentageOne" />
      <Binding Path="PercentageTwo"/>
    </MultiBinding>
</TextBox.Text>
Run Code Online (Sandbox Code Playgroud)

关于Run.Text - 您无法绑定它,但有一些解决方法:

  • {}必须告诉WPF不要将{something}视为标记扩展. (10认同)

Dav*_*ave 11

我将拆分成多个文本块,在绑定中将每个文本块与StringFormat = {0:P}绑定在一起,如下所示:

<TextBox Text="{Binding Something, StringFormat=\{0:P\}}" />
Run Code Online (Sandbox Code Playgroud)

有关示例,请参阅此文章:Lester在StringFormat上的WPF博客

Checkout VS2010 - 属性绑定包括选项中的格式.