WPF学习笔记10. Binding (3)
2010-10-11 16:29:53 来源:本站整理当然,我们也可以使用 CSS 那样的选择器来指定模板的应用类型,而不是在 ListBox 上设置 ItemTemplate 属性。
<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>
<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}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel DataContext="{StaticResource personals}">
<ListBox x:Name="listbox1" ItemsSource="{Binding}">
</ListBox>
</StackPanel>
</Grid>
</Window>
通过 DataType="{x:Type my:Personal}" 我们就可以让所有使用 Personal 对象的地方自动使用这个模板设置。
利用数据模板,我们还可以做出复杂的效果来,比如根据 Personal.Sex 来显示一个不同颜色的边框。类似的做法在 WinForm 似乎很麻烦,现在只需做些简单的设置即可。
<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>
<DataTemplate DataType="{x:Type my:Personal}">
<Border x:Name="border1" BorderBrush="Red" BorderThickness="1" Padding="5" Margin="5">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock>,</TextBlock>
<TextBlock Text="{Binding Path=Age}" />
<TextBlock>,</TextBlock>
<TextBlock Text="{Binding Path=Sex}" />
</StackPanel>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Sex}">
<DataTrigger.Value>Male</DataTrigger.Value>
<Setter TargetName="border1" Property="BorderBrush" Value="Blue" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel DataContext="{StaticResource personals}">
<ListBox x:Name="listbox1" ItemsSource="{Binding}">
</ListBox>
</StackPanel>
</Grid>
</Window>
首先,我们在数据模板中增加了一个 Border,默认颜色是红色。然后利用触发器,当 Personal.Sex == Male 时,将边框颜色设置为蓝色。
更多精彩
赞助商链接