WPF 体验---数据邦定(二)
上一节,提到了控制空值的TargetNullValue。本节介绍下另外两个跟绑定有关的关键字:StringFormat,FallbackValue。
StringFormat,顾名思义就是格式化字符串,在数据绑定的过程中,这个当然很重要了,谁不爱美阿。先看看上节的例子:
<Window x:Class="WpfProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox Name="lbxPersons">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}" Width="50" />
<TextBlock Text="{Binding LastName}" Width="50" />
<TextBlock Text="{Binding Age, TargetNullValue='Age Unknown'}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
为了很好的显示我们所需要的数据,用了三个TextBlock,显得很啰嗦有很吃力,那么有没有更好的方法呢,用MultiBinding和StringFormat。
代码
<Window x:Class="WpfProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="clr-namespace:System.Windows.Data;assembly=PresentationFramework"
Title="Test" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox Name="lbxPersons">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}-{1},{2}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
<Binding Path="Age" TargetNullValue='Age Unknown'/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
FallbackValue设置邦定不存在时显示的信息。还是上面的例子,Person类里不存在Birthday属性,我们在绑定里添加,让它显示不存在。
代码
运行:
<Window x:Class="WpfProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox Name="lbxPersons">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}-{1},{3},{2}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
<Binding Path="Age" TargetNullValue='Age Unknown'/>
<Binding Path="Birthday" FallbackValue='Birthday Unknown'/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
OK。