当前位置:编程学习 > asp >>

继续聊WPF——动态数据模板

   我为啥称之为“动态数据模板”?先看看下面的截图,今天,我们就是要实现这种功能。
 
 
 \
 
 
大概是这样的,我们定义的DataTemplate是通过触发器动态应用到ComboBoxItem 上。
 
这个下拉列表控件绑定了一个Person集合,Person类的定义如下:
 
 
[csharp]
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定义一个处于高亮状态时使用的数据模板,也就是当鼠标移到项上时发生。
[html]
<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 定义一个样式。
[html]
<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。
[html]
<Grid> 
    <ComboBox x:Name="cmb" Margin="10,10" 
              Height="24" Width="200" 
              HorizontalAlignment="Left" 
&nb
补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,