使用 StringFormat 将字符串添加到 WPF XAML 绑定 [英] Use StringFormat to add a string to a WPF XAML binding

查看:54
本文介绍了使用 StringFormat 将字符串添加到 WPF XAML 绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WPF 4 application that contains a TextBlock which has a one-way binding to an integer value (in this case, a temperature in degrees Celsius). The XAML looks like this:

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

这适用于显示实际温度值,但我想格式化这个值,以便它包括°C 而不仅仅是数字(30°C 而不是 30).我一直在阅读有关 StringFormat 的文章,并且看到了几个这样的通用示例:

This works fine for displaying the actual temperature value but I'd like to format this value so it includes °C instead of just the number (30°C instead of just 30). I've been reading about StringFormat and I've seen several generic examples like this:

// 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}}"/>

不幸的是,我所见过的所有示例都没有像我试图做的那样将字符串附加到绑定值.我确定它一定很简单,但我没有运气找到它.谁能向我解释如何做到这一点?

Unfortunately, none of the examples I've seen have appended a string to the bound value as I'm trying to do. I'm sure it's got to be something simple but I'm not having any luck finding it. Can anyone explain to me how to do that?

推荐答案

您的第一个示例实际上是您所需要的:

Your first example is effectively what you need:

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

这篇关于使用 StringFormat 将字符串添加到 WPF XAML 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆