bmt*_*033 114 c# data-binding wpf xaml string-formatting
我有一个WPF 4应用程序,其中包含一个TextBlock,它具有一个单向绑定到一个整数值(在这种情况下,温度为摄氏度).XAML看起来像这样:
<TextBlock x:Name="textBlockTemperature">
<Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>
Run Code Online (Sandbox Code Playgroud)
这适用于显示实际温度值,但我想格式化这个值,因此它包括°C而不是数字(30°C而不是30°).我一直在阅读有关StringFormat的文章,我看过几个这样的通用例子:
// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />
Run Code Online (Sandbox Code Playgroud)
和
// preface the bound value with a string and format it as a currency
<TextBlock Text="{Binding Amount, StringFormat=Amount: {0:C}}"/>
Run Code Online (Sandbox Code Playgroud)
不幸的是,我所看到的所有例子都没有在我试图做的事情中附加一个字符串到绑定值.我敢肯定它必须简单但我找不到任何运气.任何人都可以向我解释如何做到这一点?
Ree*_*sey 198
您的第一个例子实际上是您所需要的:
<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
Run Code Online (Sandbox Code Playgroud)
den*_*zov 98
如果你在字符串的中间或多个绑定中有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>
Run Code Online (Sandbox Code Playgroud)
小智 80
请注意,在Bindings中使用StringFormat似乎只适用于"text"属性.将它用于Label.Content将不起作用
| 归档时间: |
|
| 查看次数: |
152566 次 |
| 最近记录: |