C# 使用 StringFormat 将字符串添加到 WPF XAML 绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19278515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use StringFormat to add a string to a WPF XAML binding
提问by bmt22033
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:
我有一个 WPF 4 应用程序,其中包含一个 TextBlock,它具有与整数值的单向绑定(在这种情况下,以摄氏度为单位的温度)。XAML 看起来像这样:
<TextBlock x:Name="textBlockTemperature">
<Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>
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:
这适用于显示实际温度值,但我想格式化这个值,以便它包括°C 而不仅仅是数字(30°C 而不是 30)。我一直在阅读有关 StringFormat 的文章,并且看到了几个这样的通用示例:
// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />
and
和
// 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?
不幸的是,我所见过的所有示例都没有像我试图做的那样将字符串附加到绑定值。我确定它一定很简单,但我没有运气找到它。谁能向我解释如何做到这一点?
采纳答案by Reed Copsey
Your first example is effectively what you need:
您的第一个示例实际上是您所需要的:
<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
回答by denis morozov
Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:
如果您在字符串中间有 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>
回答by Rajesh Nath
In xaml
在 xaml 中
<TextBlock Text="{Binding CelsiusTemp}" />
In ViewModel
, this way setting the value also works:
在 中ViewModel
,以这种方式设置值也有效:
public string CelsiusTemp
{
get { return string.Format("{0}°C", _CelsiusTemp); }
set
{
value = value.Replace("°C", "");
_CelsiusTemp = value;
}
}
回答by Casper Ehrenborg
Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Contentwill not work
请注意,在 Bindings 中使用 StringFormat 似乎只适用于“文本”属性。将此用于 Label.Content将不起作用