Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用StringFormat向WPF XAML绑定添加字符串_C#_Wpf_Xaml_Data Binding_String Formatting - Fatal编程技术网

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

C# 使用StringFormat向WPF XAML绑定添加字符串,c#,wpf,xaml,data-binding,string-formatting,C#,Wpf,Xaml,Data Binding,String Formatting,我有一个WPF4应用程序,它包含一个TextBlock,该TextBlock具有一个指向整数值的单向绑定(在本例中,是以摄氏度为单位的温度)。XAML如下所示: <TextBlock x:Name="textBlockTemperature"> <Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock> // format the bound value as a currency

我有一个WPF4应用程序,它包含一个TextBlock,该TextBlock具有一个指向整数值的单向绑定(在本例中,是以摄氏度为单位的温度)。XAML如下所示:

<TextBlock x:Name="textBlockTemperature">
        <Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>
// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />

这对于显示实际温度值很好,但我想格式化此值,使其包含°C而不仅仅是数字(30°C而不仅仅是30°)。我一直在阅读关于StringFormat的文章,我看到了几个类似这样的通用示例:

<TextBlock x:Name="textBlockTemperature">
        <Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>
// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />
//将绑定值格式化为货币

//在绑定值前面加一个字符串,并将其格式化为货币

不幸的是,我所看到的示例中没有一个像我所尝试的那样向绑定值追加字符串。我相信一定是简单的,但我找不到。有人能告诉我怎么做吗?

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

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


这里有一个替代方案,如果在字符串中间或多个绑定中绑定,则可读性很好:

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

请注意,在绑定中使用StringFormat似乎只适用于“文本”属性。不起作用

我更喜欢这个答案,因为我可以轻松插入字符串库中的文本。当然,如果您真的担心国际化,那么最好使用转换器,这样数字和单位的顺序就不会固定。这是一个很好的解决方案,但我在最终文本显示中得到了额外的空间,在文本运行之间-知道为什么吗?在您的示例中,我看到
0°C(32°F)
如果您想要进行实际的字符串格式设置(即控制小数位数等),那么它并不是非常有用。@Conrad如果您不想要每次运行之间的空格,您应该将这些运行放在一行上,如下所示:为什么xaml中的字符串格式的前导是空的
{}
?@Jonesopolis它在文档中-但是如果您的格式字符串以
{
开头,它提供了一种转义机制,因为
{}
在xaml中已经有了意义。我不知道文档在哪里解释了前导的{}@Eric喜欢很多文档,它很臭-他们演示了它,但没有解释。这里是神秘的{}文档:一个非常重要的点,我一直在尝试,直到我绝望,并发现这个评论来验证我的怀疑。
ContentStringFormat
解救了我,例如:
Content=“{Binding Path=TargetProjects.Count}“ContentStringFormat=“Projects:{0}”
。感谢真正的英雄卡斯珀发布这些信息。对于GridViewColumn标题,请使用
HeaderStringFormat=“{}{0}作为报告”
如果您使用的是设计时数据,那么您似乎需要在编辑ContentStringFormat后重新构建项目,以使更改反映在设计器中,而在上一个文本框中使用的StringFormat将实时更新设计器。这与整个视点视图模型分离背道而驰有时“黑客”是可行的,为什么不呢?