案例地址:GitHub - microsoft/WPF-Samples: Repository for WPF related samples
一、运行界面
二、案例功能描述
数据绑定时设置字符串的格式
三、分析代码
WPF中StringFormat的用法:https://www.cnblogs.com/zhengwen/archive/2010/06/19/1761036.html
1、数据
public class ItemsForSale : ObservableCollection<PurchaseItem>
{
public ItemsForSale()
{
Add((new PurchaseItem("Snowboard and bindings", 120, new DateTime(2009, 1, 1))));
Add((new PurchaseItem("Inside C#, second edition", 10, new DateTime(2009, 2, 2))));
Add((new PurchaseItem("Laptop - only 1 year old", 499.99, new DateTime(2009, 2, 28))));
Add((new PurchaseItem("Set of 6 chairs", 120, new DateTime(2009, 2, 28))));
Add((new PurchaseItem("My DVD Collection", 15, new DateTime(2009, 1, 1))));
Add((new PurchaseItem("TV Drama Series", 39.985, new DateTime(2009, 1, 1))));
Add((new PurchaseItem("Squash racket", 60, new DateTime(2009, 2, 28))));
}
}
2、设置ListView的数据
<ListView ItemsSource="{StaticResource MyData}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=Description}"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Price, StringFormat=Now {0:c}!}"/>
</GridView>
</ListView.View>
</ListView>
3、设置ListBox的数据
<ListBox ItemsSource="{StaticResource MyData}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} -- Now only {1:C}!">
<Binding Path="Description"/>
<Binding Path="Price"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>