我有一个 WPF 4 应用程序,其中包含一个 TextBlock,它单向绑定到整数值(在本例中为摄氏度温度)。 XAML 看起来像这样:
<TextBlock x:Name="textBlockTemperature">
<Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>
这对于显示实际温度值来说效果很好,但我想格式化该值,使其包含°C而不仅仅是数字(30°C而不只是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}}"/>
不幸的是,我见过的所有示例都没有像我尝试那样将字符串附加到绑定值。我确信它一定很简单,但我没有运气找到它。谁能向我解释一下该怎么做吗?
您的第一个示例实际上就是您所需要的:
<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;
}
}