As we saw in the previous chapters, the way to manipulate the output of a binding before is shown is typically through the use of a converter. The cool thing about the converters is that they allow you to convert any data type into a completely different data type. However, for more simple usage scenarios, where you just want to change the way a certain value is shown and not necessarily convert it into a different type, the StringFormat property might very well be enough.

Using the StringFormat property of a binding, you lose some of the flexibility you get when using a converter, but in return, it's much simpler to use and doesn't involve the creation of a new class in a new file.

The StringFormat property does exactly what the name implies: It formats the output string, simply by calling the String.Format method. Sometimes an example says more than a thousand words, so before I hit that word count, let's jump straight into an example:

<Window x:Class="WpfTutorialSamples.DataBinding.StringFormatSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="StringFormatSample" Height="150" Width="250"
Name="wnd">
<StackPanel Margin="10">
<TextBlock Text="{Binding ElementName=wnd, Path=ActualWidth, StringFormat=Window width: {0:#,#.0}}" />
<TextBlock Text="{Binding ElementName=wnd, Path=ActualHeight, StringFormat=Window height: {0:C}}" />
<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}" />
<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Time: {0:HH:mm}}" />
</StackPanel>
</Window>

 

 

The first couple of TextBlock's gets their value by binding to the parent Window and getting its width and height. Through the StringFormat property, the values are formatted. For the width, we specify a custom formatting string and for the height, we ask it to use the currency format, just for fun. The value is saved as a double type, so we can use all the same format specifiers as if we had called double.ToString(). You can find a list of them here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Also notice how I can include custom text in the StringFormat - this allows you to pre/post-fix the bound value with text as you please. When referencing the actual value inside the format string, we surround it by a set of curly braces, which includes two values: A reference to the value we want to format (value number 0, which is the first possible value) and the format string, separated by a colon.

 

For the last two values, we simply bind to the current date (DateTime.Now) and the output it first as a date, in a specific format, and then as the time (hours and minutes), again using our own, pre-defined format. You can read more about DateTime formatting here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Formatting without extra text

Please be aware that if you specify a format string that doesn't include any custom text, which all of the examples above does, then you need to add an extra set of curly braces, when defining it in XAML. The reason is that WPF may otherwise confuse the syntax with the one used for Markup Extensions. Here's an example:

<Window x:Class="WpfTutorialSamples.DataBinding.StringFormatSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="StringFormatSample" Height="150" Width="250"
Name="wnd">
<WrapPanel Margin="10">
<TextBlock Text="Width: " />
<TextBlock Text="{Binding ElementName=wnd, Path=ActualWidth, StringFormat={}{0:#,#.0}}" />
</WrapPanel>
</Window>

Using a specific Culture

If you need to output a bound value in accordance with a specific culture, that's no problem. The Binding will use the language specified for the parent element, or you can specify it directly for the binding, using the ConverterCulture property. Here's an example:

<Window x:Class="WpfTutorialSamples.DataBinding.StringFormatCultureSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="StringFormatCultureSample" Height="120" Width="300">
<StackPanel Margin="10">
<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='de-DE', StringFormat=German date: {0:D}}" />
<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='en-US', StringFormat=American date: {0:D}}" />
<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='ja-JP', StringFormat=Japanese date: {0:D}}" />
</StackPanel>
</Window>

It's pretty simple: By combining the StringFormat property, which uses the D specifier (Long date pattern) and the ConverterCulture property, we can output the bound values in accordance with a specific culture. Pretty nifty!

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

The StringFormat property的更多相关文章

  1. 【WPF系列】Textbox

    Style定义实例 给Textbox定义一个阴影效果. <Style x:Key="{x:Type TextBox}" TargetType="{x:Type Te ...

  2. 同时使用Binding&StringFormat 显示Text【项目】

    Case ID (?unit) 红色的字根据一个后台boolean来做trigger,可以是Case or Open 蓝色的字binding到后台的一个string属性来切换任意的Unit单位 这样一 ...

  3. wpf Content数据绑定StringFormat起作用的原理和解决(转)

    1.简单示例: <Window x:Class="WpfOne.Bind.Bind6" xmlns="http://schemas.microsoft.com/wi ...

  4. wpf数据绑定 - StringFormat的妙用

    写在前面 WPF中常常有这样的情况:需要在UI上显示一些信息,比如显示一张图片的信息,信息结构是: 图片名:Xxx 图片尺寸:Xxx 而其中的 Xxx 通常通过数据绑定来获得, Xxx 前面的内容是需 ...

  5. wpf Content数据绑定StringFormat起作用的原理和解决

    原文:wpf Content数据绑定StringFormat起作用的原理和解决 <Window x:Class="WpfOne.Bind.Bind6" xmlns=" ...

  6. How do you create a DynamicResourceBinding that supports Converters, StringFormat?

    原文 How do you create a DynamicResourceBinding that supports Converters, StringFormat? 2 down vote ac ...

  7. 探究@property申明对象属性时copy与strong的区别

    一.问题来源 一直没有搞清楚NSString.NSArray.NSDictionary--属性描述关键字copy和strong的区别,看别人的项目中属性定义有的用copy,有的用strong.自己在开 ...

  8. JavaScript特性(attribute)、属性(property)和样式(style)

    最近在研读一本巨著<JavaScript忍者秘籍>,里面有一篇文章提到了这3个概念. 书中的源码可以在此下载.我将源码放到了线上,如果不想下载,可以直接访问在线网址,修改页面名就能访问到相 ...

  9. -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HO 解决办法

    最近在使用maven,项目测试的时候出现了这么一个错.-Dmaven.multiModuleProjectDirectory system property is not set. Check $M2 ...

随机推荐

  1. JS_ECMA基本语法中的几种封装的小函数-1

    今天给大家介绍js ECMA中几个封装的小函数以及一些常用的函数小案例: 1,找重复的函数 <script> //在数组里面找重复: function findInArr(n,arr){ ...

  2. Quartus 11.0 的AS 下载方式和JTAG下载jic文件的方式

    FPGA下载的三种方式:主动配置方式(AS)和被动配置方式(PS)和最常用的(JTAG)配置方式: AS由FPGA器件引导配置操作过程,它控制着外部存储器和初始化过程,EPCS系列.如EPCS1,EP ...

  3. Linux下多窗口分屏式终端--Terminator

    很不错的分屏插件终端:https://pkgs.org/centos-6/repoforge-i386/terminator-0.95-3.el6.rf.noarch.rpm.html

  4. Spring学习笔记—Spring之旅

    1.Spring简介     Spring是一个开源框架,最早由Rod Johnson创建,并在<Expert One-on-One:J2EE Design and Development> ...

  5. html 中几次方,平方米,立方米,下标,上标,删除线等的表示方法

    html 中几次方,平方米,立方米,上标,下标,删除线等的表示方法 上标下标删除线 小号字  M2 54 X24+Y1<3=100 NN <sup>上标</sup> &l ...

  6. Linux Shell 高级编程技巧4----几个常用的shell脚本例子

    4.几个常用的shell脚本例子    4.0.在写脚本(同样适用在编程的时候),最好写好完善的注释    4.1.kill_processes.sh(一个杀死进程的脚本) #!/bin/bash c ...

  7. php判断当前的访问是手机还是电脑

    <?php function check_wap() { if (isset($_SERVER['HTTP_VIA'])) return true; if (isset($_SERVER['HT ...

  8. 手机WEB自适应头部代码

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> < ...

  9. hdu 4738 2013杭州赛区网络赛 桥+重边+连通判断 ***

    题意:有n座岛和m条桥,每条桥上有w个兵守着,现在要派不少于守桥的士兵数的人去炸桥,只能炸一条桥,使得这n座岛不连通,求最少要派多少人去. 处理重边 边在遍历的时候,第一个返回的一定是之前去的边,所以 ...

  10. hdu 4007 暴力or线段树 ***

    尼玛,INF不能定义太大,找标程对拍了好久 #include<cstdio> #include<iostream> #include<algorithm> #inc ...