WPF DataTemplate 数据模板

DataTemplate 顾名思义,数据模板,在 wpf 中使用非常频繁。

它一般用在带有 DataTemplate 依赖属性的控件中,如 ContentControl、集合控件 ListBox、ItemsControl 、TabControls 等。

1. 非集合控件中使用

xml 复制代码
<UserControl.Resources>
    <DataTemplate x:Key="MyDataTemplate">
        <Grid
            Width="100"
            Height="40"
            Background="DeepPink" />
    </DataTemplate>
</UserControl.Resources>

在前端代码中,应用这个数据模板,

xml 复制代码
<ContentControl ContentTemplate="{StaticResource MyDataTemplate}" />

显示如下:

2. 集合控件中使用

以 ListBox 为例,

假设 ListBox 绑定数据源为下面的 MyItems ,

csharp 复制代码
public class DataTemplateViewModel
{
    public IList<string> MyItems { get; }
    
    public DataTemplateViewModel()
    {
        MyItems = new List<string>() { "Tom~", "Jerry~"};
    }
}
xml 复制代码
<ListBox
    Grid.Column="1"
    ItemsSource="{Binding MyItems}" />

在不设置数据模板的情况下,默认就是显示字符串,

新增一个数据模板,

xml 复制代码
<UserControl.Resources>
    <DataTemplate x:Key="MyDataTemplate">
        <Grid
            Width="100"
            Height="40"
            Background="DeepPink">
            <TextBlock Text="{Binding .}" Foreground="Yellow" />
        </Grid>
    </DataTemplate>
</UserControl.Resources>

并应用该模板后,

xml 复制代码
<ListBox
    Grid.Column="1"
    ItemTemplate="{StaticResource MyDataTemplate}"
    ItemsSource="{Binding MyItems}" />

显示为,

通过上面的例子,我们可以知道,数据模板,可以用来自定义数据展示的方式,包括:格式、效果、样式等。

3. DataTempate 其它用法

3.1 自动匹配数据类型

上面演示的集合中使用 DataTemplate 的方式,数据类型相对简单。实际开发中经常要根据不同数据类型,展示不同数据样式。

假设申明一个图形接口,

csharp 复制代码
public interface IShape
{
    string Color { get; }
}

一个圆、矩形类各自实现该接口,

csharp 复制代码
public class Circle : IShape
{
    public string Color { get; }

    public Circle(string color)
    {
        Color = color;
    }
}

public class Rectange : IShape
{
    public string Color { get; }

    public Rectange(string color)
    {
        Color = color;
    }
}

集合 Shapes 中包含这些图形实例,

csharp 复制代码
public class DataTemplateViewModel
{
    public IList<IShape> Shapes { get; }

    public DataTemplateViewModel()
    {
        Shapes = new List<IShape>()
        {
            new Circle("#CC0066"),
            new Rectange("#009900"),
        };
    }
}

设置 DataTemplate 的 DataType 属性(不设置 x:key),就可以根据图形类型,自动应用对应数据模板,

xml 复制代码
<ListBox
    Grid.Column="1"
    ItemsSource="{Binding Shapes}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type views:Circle}">
            <Ellipse Width="60" Height="60" Fill="{Binding Color}" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type views:Rectange}">
            <Rectangle Width="60" Height="60" Fill="{Binding Color}" />
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

效果如下,

3.2 DataTemplateSelector

使用 DataTemplateSelector (模板选择器)也可以同样实现上面的效果。

我们只需要继承 DataTemplateSelector 类,并重载其 SelectTemplate 方法,

csharp 复制代码
public class MyDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate CircleTemplate { get; set; }
    public DataTemplate RectTemplate { get; set; }
    public DataTemplate EmptyTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is Circle)
        {
            return CircleTemplate;
        }
        else if (item is Rectange)
        {
            return RectTemplate;
        }

        return EmptyTemplate;
    }
}

数据模板 + 选择器 前端定义,这时就要设置 DataTemplate 的 x:key 了,

xml 复制代码
<UserControl.Resources>
    <DataTemplate x:Key="Circle.DataTemplate">
        <Ellipse Width="60" Height="60" Fill="{Binding Color}" />
    </DataTemplate>

    <DataTemplate x:Key="Rectangle.DataTemplate">
        <Rectangle Width="60" Height="60" Fill="{Binding Color}" />
    </DataTemplate>

    <DataTemplate x:Key="Empty.DataTemplate">
        <Grid Width="60" Height="60" Background="Black" />
    </DataTemplate>

    <views:MyDataTemplateSelector x:Key="MyDataTemplateSelector" 
                                  CircleTemplate="{StaticResource Circle.DataTemplate}"
                                  RectTemplate="{StaticResource Rectangle.DataTemplate}" 
                                  EmptyTemplate="{StaticResource Empty.DataTemplate}" />
</UserControl.Resources>

应用选择器,

xml 复制代码
<ListBox
    Grid.Column="1"
    ItemTemplateSelector="{StaticResource MyDataTemplateSelector}"
    ItemsSource="{Binding Shapes}">
</ListBox>

新增一个 null 元素配合实验,

csharp 复制代码
Shapes = new List<IShape>()
{
    new Circle("#CC0066"),
    new Rectange("#009900"),
    null,
};

显示效果,

相关推荐
大道随心7 小时前
【wpf】11 在WPF中实现父窗口蒙版效果:原理详解与进阶优化
wpf
zizisuo1 天前
9.1.领域驱动设计
wpf
大道随心1 天前
【wpf】10 C#树形控件高效实现:递归构建与路径查找优化详解
开发语言·c#·wpf
离歌漠1 天前
WPF内嵌其他进程的窗口
c#·wpf
沉到海底去吧Go1 天前
【身份证识别表格】批量识别身份证扫描件或照片保存为Excel表格,怎么大批量将身份证图片转为excel表格?基于WPF和腾讯OCR的识别方案
ocr·wpf·excel·身份证识别表格·批量扫描件身份证转表格·图片识别表格·图片识别excel表格
csdn_aspnet2 天前
WPF 性能 UI 虚拟化 软件开发人员的思考
ui·wpf
冰茶_2 天前
WPF之绑定模式深入
学习·microsoft·微软·c#·wpf·绑定模式
Vae_Mars2 天前
WPF中如何自定义控件
wpf
冰茶_2 天前
WPF之集合绑定深入
microsoft·微软·c#·wpf·mvvm·数据绑定·布局系统
凌霜残雪2 天前
WPF 3D图形编程核心技术解析
3d·wpf