我为啥称之为“动态数据模板”?先看看下面的截图,今天,我们就是要实现这种功能。
大概是这样的,我们定义的DataTemplate是通过触发器动态应用到 ComboBoxItem 上。
public class Person { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } public override string ToString() { return Name; } }
<Window.Resources> <!-- 当项高亮显示时使用的数据模板 --> <DataTemplate x:Key="hightlightTmp"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <StackPanel Margin="0,5,0,0" Grid.Row="0" Orientation="Horizontal"> <TextBlock Margin="2,0" FontWeight="Bold" FontSize="14"> <TextBlock.Text> <Binding Path="Name" StringFormat="姓名:{0}"/> </TextBlock.Text> </TextBlock> <TextBlock Margin="20,0"> <TextBlock.Text> <Binding Path="Age" StringFormat="年龄:{0}"/> </TextBlock.Text> </TextBlock> </StackPanel> <TextBlock Margin="0,2,0,5" Grid.Row="1"> <TextBlock.Text> <Binding Path="Email" StringFormat="电邮:{0}"/> </TextBlock.Text> </TextBlock> </Grid> </DataTemplate> .............. </Window.Resources>
<Window.Resources> ................ <!-- 项样式 --> <Style x:Key="cmbStyle" TargetType="{x:Type ComboBoxItem}"> <Style.Triggers> <Trigger Property="IsHighlighted" Value="True"> <Setter Property="ContentTemplate" Value="{StaticResource hightlightTmp}"/> </Trigger> </Style.Triggers> </Style> </Window.Resources>
<Grid> <ComboBox x:Name="cmb" Margin="10,10" Height="24" Width="200" HorizontalAlignment="Left" VerticalAlignment="Top" ItemContainerStyle="{StaticResource cmbStyle}"/> </Grid>
public Window1() { InitializeComponent(); this.cmb.ItemsSource = new Person[] { new Person{Name="小李",Age=22,Email="[email protected]"}, new Person{Name="小王",Age=20,Email="[email protected]"}, new Person{Name="黄涨",Age=21,Email="[email protected]"}, new Person{Name="高产",Age=22,Email="[email protected]"}, new Person{Name="杜林",Age=21,Email="[email protected]"}, new Person{Name="杨白姥",Age=50,Email="[email protected]"}, new Person{Name="鸟人",Age=31,Email="[email protected]"}, new Person{Name="宋小八",Age=28,Email="[email protected]"} }; }