使用 StringFormat 向 WPF XAML 绑定添加字符串

我有一个 WPF 4应用程序,其中包含一个 TextBlock,它具有一个单向绑定到一个整数值(在本例中是以摄氏度为单位的温度)。XAML 看起来像这样:

<TextBlock x:Name="textBlockTemperature">
<Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>

这对于显示实际的温度值很有用,但是我想格式化这个值,这样它就包含了摄氏度而不仅仅是数字(30摄氏度而不仅仅是30)。我一直在阅读关于 StringFormat 的文章,我看到了一些这样的通用示例:

// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />

还有

// preface the bound value with a string and format it as a currency
<TextBlock Text="{Binding Amount, StringFormat=Amount: {0:C}}"/>

不幸的是,我所看到的示例中没有一个像我正在尝试的那样在绑定值后面添加字符串。我知道肯定很简单,但我找不到。有人能给我解释一下怎么做吗?

233670 次浏览

你的第一个例子就是你所需要的:

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

如果在字符串或多个绑定中间使用 Binding,这里有一个可以很好地提高可读性的替代方法:

<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>

在 xaml

<TextBlock Text="{Binding CelsiusTemp}" />

ViewModel中,这种设置值的方法同样有效:

 public string CelsiusTemp
{
get { return string.Format("{0}°C", _CelsiusTemp); }
set
{
value = value.Replace("°C", "");
_CelsiusTemp = value;
}
}

请注意,在绑定中使用 StringFormat 似乎只对“文本”属性有效。 对 Label.Content 使用此方法不起作用