WPF学习笔记10. Binding (3)
2010-10-11 16:29:53 来源:本站整理7. 值转换器
某些时候,我们需要对绑定的源值进行类型或者显示格式转换,那么可以采用值转换器达到这个目的。比如我们可以将上面的 Sex 转换成 "男"、"女" 来显示。
Window1.xaml.cs
public class SexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString() == "Male" ? "男" : "女";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
转换器很简单,只需实现 IValueConverter 接口即可。
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Learn.WPF"
Title="Window1">
<Window.Resources>
<my:PersonalList x:Key="personals" >
<my:Personal Name="Tom" Age="10" Sex="Male" />
<my:Personal Name="Mary" Age="15" Sex="Female" />
<my:Personal Name="Jack" Age="12" Sex="Male" />
</my:PersonalList>
<my:SexConverter x:Key="sexConverter" />
<DataTemplate DataType="{x:Type my:Personal}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock>,</TextBlock>
<TextBlock Text="{Binding Path=Age}" />
<TextBlock>,</TextBlock>
<TextBlock Text="{Binding Path=Sex, Converter={StaticResource sexConverter}}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel DataContext="{StaticResource personals}">
<ListBox x:Name="listbox1" ItemsSource="{Binding}">
</ListBox>
</StackPanel>
</Grid>
</Window>
首先在资源中创建一个转换器实例,然后在数据模板中使用 Binding.Converter 来指定转换器实例即可。看看最终效果。
更多精彩
赞助商链接