我为啥称之为“动态数据模板”?先看看下面的截图,今天,我们就是要实现这种功能。
大概是这样的,我们定义的DataTemplate是通过触发器动态应用到 ComboBoxItem 上。
这个下拉列表控件绑定了一个Person集合,Person类的定义如下:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public override string ToString()
{
return Name;
}
}
这里重写了ToString方法,因为ComboBox生成的项是调用对象的ToString方法的,为了能不设置数据模板的前提下正确显示列表项,需要重写ToString方法,默认显示姓名属性。
然后,我们为ComboBoxItem定义一个处于高亮状态时使用的数据模板,也就是当鼠标移到项上时发生。
<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>
为 ComboBoxItem 定义一个样式。
<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>
在窗体中声明一个ComboBox。
<Grid>
<ComboBox x:Name="cmb" Margin="10,10"
Height="24" Width="200"
HorizontalAlignment="Left"
VerticalAlignment="Top"
ItemContainerStyle="{StaticResource cmbStyle}"/>
</Grid>
最后,切换到代码视图,完成设置数据源的C#代码。
public Window1()
{
InitializeComponent();
this.cmb.ItemsSource = new Person[]
{
new Person{Name="小李",Age=22,Email="suk211@163.com"},
new Person{Name="小王",Age=20,Email="minat@126.com"},
new Person{Name="黄涨",Age=21,Email="laned2@21cn.com"},
new Person{Name="高产",Age=22,Email="ha@136.com"},
new Person{Name="杜林",Age=21,Email="null@yaahoo.com"},
new Person{Name="杨白姥",Age=50,Email="cYang@21cn.com"},
new Person{Name="鸟人",Age=31,Email="bgl@ask.net.cn"},
new Person{Name="宋小八",Age=28,Email="xde227@123h.com"}
};
}
完成,这时候运行一下,你会看到上文中截图中的效果了。