浅谈WPF之控件模板Control Template和数据模板Data Template

WPF不仅支持传统的Windows Forms编程的用户界面和用户体验设计,同时还推出了以模板为核心的新一代设计理念。在WPF中,通过引入模板,将数据和算法的“内容”和“形式”进行解耦。模板主要分为两大类:数据模板【Data Template】和控件模板【Control Template】

基本上,ControlTemplate描述如何显示控件,而DataTemplate描述如何显示数据

控件模板 Control Template


控件模板让我们可以定义控件的外观,改变控件的展现形式,通过Control Template实现。

1. 编辑默认模板

 选中控件--右键--编辑模板--编辑副本,打开创建Style资源对话框,如下所示:

创建Style资源,输入资源名称,定义位置,默认为此文档【Window】,然后点击【确定】,创建资源。如下所示: 

创建控件元素的默认资源,如下所示: 


<Window x:Class="WpfApp2.TwoWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp2"mc:Ignorable="d"Title="TwoWindow" Height="350" Width="800"><Window.Resources><Style x:Key="FocusVisual"><Setter Property="Control.Template"><Setter.Value><ControlTemplate><Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/></ControlTemplate></Setter.Value></Setter>
</Style><SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/><SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/><SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/><SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/><SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/><SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/><SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/><SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/><SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/><Style x:Key="OneButtonStyle" TargetType="{x:Type Button}"><Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/><Setter Property="Background" Value="{StaticResource Button.Static.Background}"/><Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/><Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/><Setter Property="BorderThickness" Value="1"/><Setter Property="HorizontalContentAlignment" Value="Center"/><Setter Property="VerticalContentAlignment" Value="Center"/><Setter Property="Padding" Value="1"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Button}"><Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true"><ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Border><ControlTemplate.Triggers><Trigger Property="IsDefaulted" Value="true"><Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/></Trigger><Trigger Property="IsMouseOver" Value="true"><Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/><Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/></Trigger><Trigger Property="IsPressed" Value="true"><Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/><Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/></Trigger><Trigger Property="IsEnabled" Value="false"><Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/><Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/><Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
</Style></Window.Resources><Grid><Button x:Name="one" Content="Hello wpf" Margin="5" Width="100" Height="30" Style="{DynamicResource OneButtonStyle}"></Button></Grid>
</Window>

2. 修改默认样式

通过默认创建的控件模板Style,可以修改和重定义控件的显示内容,如:设置按钮显示圆角,和鼠标放上去为红色。

 要实现以上功能,只需要修改两个地方即可,如下所示:

3. 自定义控件模板

通过自定义模板,同样能达到修改控件样式的效果。

控件模板也是资源的一种,每一个控件模板都有一个唯一的key,在控件上通过Template进行绑定,如下所示:


<Window x:Class="WpfApp2.ThreeWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp2"mc:Ignorable="d"Title="自定义控件模板示例" Height="150" Width="300"><Window.Resources><ControlTemplate x:Key="oneStyle" TargetType="Button"><Border Background="LightBlue" CornerRadius="5" x:Name="border"><StackPanel Orientation="Horizontal" HorizontalAlignment="{TemplateBinding HorizontalAlignment}"><TextBlock VerticalAlignment="{TemplateBinding VerticalAlignment}">》》</TextBlock><ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}"></ContentPresenter></StackPanel></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="true"><Setter Property="Background" TargetName="border" Value="Red"/><Setter Property="BorderBrush" TargetName="border" Value="Blue"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Window.Resources><Grid><Button x:Name="one" Content="Hello wpf" Margin="5" Width="100" Height="30" VerticalAlignment="Center"  HorizontalAlignment="Center" Template="{StaticResource oneStyle}"></Button></Grid>
</Window>

 自定义控件模板,示例如下:

数据模板 DataTemplate 

控件模板决定了数据的展示形式和用户体检,在软件UI设计中非常重要。同样数据的展示形式越来越多样化,正所谓:横看成岭侧成峰,远近高低各不同。同样的数据内容,在DataGrid中的展示是文本的列表形式,在ComboBox中是下拉框的形式。给数据披上外衣,将数据和形式解耦,是一种新的发展趋势。

1. DataGrid

a. 数据模板

DataGrid是可以自定义网格数据显示的控件,通过自定义显示的列模板,可以实现各式各样的展现方式。列定义如下:

  1. DataGrid的列定义,通过Binding="{Binding Name}"的方式绑定属性,通过ElementStyle="{StaticResource one_center}"的方式绑定样式。

  2. DataGrid预制了几种列展示数据的方式,如:DataGridTextColumn【文本】,DataGridCheckBoxColumn【复选框】,DataGridComboBoxColumn【下拉框】,DataGridHyperlinkColumn【链接】等,如果使用数据模板,则采用DataGridTemplateColumn进行定义。

UI示例如下所示:

<Window x:Class="WpfApp2.A1Window"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp2"mc:Ignorable="d"Title="数据模板示例" Height="450" Width="650"><Window.Resources><Style x:Key="one_center" TargetType="TextBlock"><Setter Property="VerticalAlignment" Value="Center"></Setter><Setter Property="HorizontalAlignment" Value="Center"></Setter>
</Style><Style x:Key="one_header" TargetType="DataGridColumnHeader"><Setter Property="VerticalAlignment" Value="Center"></Setter><Setter Property="HorizontalAlignment" Value="Center"></Setter><Setter Property="HorizontalContentAlignment" Value="Center"></Setter><Setter Property="BorderThickness" Value="0"></Setter>
</Style></Window.Resources><Grid><DataGrid x:Name="one"  Margin="10" AutoGenerateColumns="False"  CanUserAddRows="False"  CanUserSortColumns="False" BorderThickness="0" ><DataGrid.Columns><DataGridTextColumn Header="姓名" Binding="{Binding Name}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"  /><DataGridTextColumn Header="年龄" Binding="{Binding Age}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"/><DataGridTextColumn Header="性别" Binding="{Binding Sex}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"/><DataGridTextColumn Header="班级" Binding="{Binding Classes}" Width="*" ElementStyle="{StaticResource one_center}" HeaderStyle="{StaticResource one_header}"/><DataGridTemplateColumn Header="操作" Width="*" HeaderStyle="{StaticResource one_header}"><DataGridTemplateColumn.CellTemplate><DataTemplate><StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center"><Button x:Name="edit" Content="编辑" Width="60" Margin="3" Height="25"></Button><Button x:Name="delete" Content="删除" Width="60" Margin="3" Height="25"></Button></StackPanel></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn></DataGrid.Columns></DataGrid></Grid>
</Window>

b. 后台数据绑定

后台数据绑定通过ItemsSource进行赋值,绑定的数据的属性名,要和DataGrid的列绑定数据的名称保持一致,如下所示:

namespace WpfApp2
{/// <summary>/// A1Window.xaml 的交互逻辑/// </summary>public partial class A1Window : Window{public A1Window(){InitializeComponent();List<Student> lst = new List<Student>();lst.Add(new Student() { Name = "张三", Age = 22, Sex = "男", Classes = "一班" });lst.Add(new Student() { Name = "李四", Age = 21, Sex = "男", Classes = "二班" });lst.Add(new Student() { Name = "王五", Age = 20, Sex = "女", Classes = "一班" });lst.Add(new Student() { Name = "刘大", Age = 19, Sex = "男", Classes = "三班" });lst.Add(new Student() { Name = "麻子", Age = 18, Sex = "男", Classes = "四班" });one.ItemsSource = lst;}}public class Student{public string Name { get; set; }public int Age { get; set; }public string Sex { get; set; }public string Classes { get; set; }}
}

 DataGrid示例,如下所示:

2. ListBox和ComboBox

a. 数据模板

ListBox,ComboBox,均是包含可选择的项的列表,只是ListBox不需要下拉显示,ComboBox需要下拉显示。通过定义数据模板,可以丰富数据的展示形式。

通过ItemTemplate="{StaticResource item_template}"的形式,进行数据模板的绑定。如下所示:

<Window x:Class="WpfApp2.A2Window"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp2"mc:Ignorable="d"Title="数据模板示例" Height="450" Width="800"><Window.Resources><DataTemplate x:Key="item_template"><StackPanel Orientation="Horizontal" Margin="5 ,0"><Border Width="10" Height="10" Background="{Binding Code}"></Border><TextBlock Text="{Binding Code}" Margin="5,0" ></TextBlock></StackPanel></DataTemplate></Window.Resources><Grid><StackPanel Margin="3" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"><ComboBox x:Name="one" Height="25" Width="120" Margin="5" ItemTemplate="{StaticResource item_template}"></ComboBox><ListBox x:Name="two"  Width="120" Margin="5" ItemTemplate="{StaticResource item_template}"></ListBox></StackPanel></Grid>
</Window>

b. 后台数据绑定

与DataGrid一样,后台通过ItemsSource进行数据的绑定。如下所示:


namespace WpfApp2
{/// <summary>/// A2Window.xaml 的交互逻辑/// </summary>public partial class A2Window : Window{public A2Window(){InitializeComponent();List<Color> lst = new List<Color>();lst.Add(new Color() { Code = "#FE8C00" });lst.Add(new Color() { Code = "#1F7F50" });lst.Add(new Color() { Code = "#AA8C00" });lst.Add(new Color() { Code = "#FEAA00" });lst.Add(new Color() { Code = "#008CAA" });lst.Add(new Color() { Code = "#FEBB00" });one.ItemsSource = lst;two.ItemsSource = lst;}}public class Color{public string Code { get; set; }}
}

 

3. ItemsControl

a. 数据模板

ItemsControl,主要用于展示集合数据的项,也是列表控件的一种。ItemsControl 需要设置两个内容:

  • ItemsControl.ItemsPanel,做为数据展示的容器。

  • ItemsControl.ItemTemplate,用于单个数据的展示形式。

具体如下所示:

<Window x:Class="WpfApp2.A3Window"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp2"mc:Ignorable="d"Title="A3Window" Height="450" Width="800"><Grid><ItemsControl x:Name="one"><ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel></WrapPanel></ItemsPanelTemplate></ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate><Button Width="50" Height="50" Margin="5" Content="{Binding Code}"></Button></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></Grid>
</Window>

b. 后台数据绑定

与DataGrid一样,后台通过ItemsSource进行数据的绑定。如下所示:


namespace WpfApp2
{/// <summary>/// A3Window.xaml 的交互逻辑/// </summary>public partial class A3Window : Window{public A3Window(){InitializeComponent();List<Test> lst = new List<Test>();lst.Add(new Test() { Code = "1" });lst.Add(new Test() { Code = "2" });lst.Add(new Test() { Code = "3" });lst.Add(new Test() { Code = "4" });lst.Add(new Test() { Code = "5" });lst.Add(new Test() { Code = "6" });one.ItemsSource = lst;}}public class Test{public string Code { get; set; }}
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/2660756.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

linux cat命令增加-f显示文件名功能

在使用cat命令配合grep批量搜索文件内容时&#xff0c;我仅仅能知道是否搜索到&#xff0c;不知道是在哪个文件里找到的。比如cat ./src/*.c | grep full_write,在src目录下的所有.c文件里找full_write,能匹配到所有的full_write&#xff0c;但是不知道它们分别在哪些文件里。于…

【八】【C语言\动态规划】1567. 乘积为正数的最长子数组长度、413. 等差数列划分、978. 最长湍流子数组,三道题目深度解析

动态规划 动态规划就像是解决问题的一种策略&#xff0c;它可以帮助我们更高效地找到问题的解决方案。这个策略的核心思想就是将问题分解为一系列的小问题&#xff0c;并将每个小问题的解保存起来。这样&#xff0c;当我们需要解决原始问题的时候&#xff0c;我们就可以直接利…

黑客攻击服务器之后如何清除痕迹?如何进行伪装和逃脱追踪?

黑客攻击服务器之后如何清除痕迹?如何进行伪装和逃脱追踪?附完整执行代码。 在攻击结束后,如何不留痕迹的清除日志和操作记录,以掩盖入侵踪迹,这其实是一个细致的技术活。你所做的每一个操作,都要被抹掉;你所上传的工具,都应该被安全地删掉。 黑客的一次攻击行为,主…

HarmonyOS应用开发-仿微信UI实现

在本篇博客中&#xff0c;介绍一个仿微信的 HarmonyOS 应用&#xff0c;应用包括微信的首页、通讯录、发现、我的页面&#xff0c;以及聊天界面。 一、先上效果图&#xff1a; 二、代码解读 以聊天界面为例&#xff0c;代码如下&#xff08;解读在代码下面&#xff09;&#…

【华为数据之道学习笔记】7-3基于物理世界的“硬感知”能力

“硬感知”能力的分类 数据采集方式主要经历了人工采集和自动采集两个阶段。自动采集技术仍在发展中&#xff0c;不同的应用领域所使用的具体技术手段也不同。基于物理世界的“硬感知”依靠的就是数据采集&#xff0c;是将物理对象镜像到数字世界中的主要通道&#xff0c;是构建…

STM32F407-14.3.10-表73具有有断路功能的互补通道OCx和OCxN的输出控制位-1x000-1x111(总结)

基于表73中&#xff0c;主输出使能&#xff08;MOE1&#xff09;的8种OCx与OCxN的输出状态及波形图&#xff0c;已经单独整理输出8篇文章&#xff0c;方便需要时单独回查。 主输出使能时&#xff08;MOE1&#xff09;总结如下 通过表73中可得以下结论 1、控制位1x000与1x100…

ffmpeg两种windows版本区别说明

版本一 必须拷贝exe和dll文件才能使用&#xff0c;如果缺少dll则exe不正正常执行 如果缺少dll &#xff0c;执行 exe会报错如下 版本2 直接拷贝exe就能使用&#xff0c;没有依赖的环境

test perf-03-性能测试之 Gatling 使用入门官方教程

quick start 快速入门 学习 Gatling 的概念&#xff0c;使用录制器创建可运行的 Gatling 仿真。 介绍 在这一部分&#xff0c;我们将使用 Gatling 进行负载测试一个简单的云托管的 Web 服务器&#xff0c;并向您介绍 DSL&#xff08;领域特定语言&#xff09;的基本要素。 …

机器学习 -- 数据预处理

系列文章目录 未完待续…… 目录 系列文章目录 前言 一、数值分析简介 二、内容 前言 tips&#xff1a;这里只是总结&#xff0c;不是教程哈。 以下内容仅为暂定&#xff0c;因为我还没找到一个好的&#xff0c;让小白&#xff08;我自己&#xff09;也能容易理解&#x…

git 如何将某个分支的某个提交复制到另外一个分支

请直接去看原文: 原文链接:git 如何将某个分支的某个提交复制到另外一个分支_gitlab里面的markdown文件可以复用其他分支的吗-CSDN博客 --------------------------------------------------------------------------------------------------------------------------------…

防火墙什么用,软件防火墙与硬件防火墙有什么不一样

防火墙是一种网络安全技术&#xff0c;通过有机结合各类用于安全管理与筛选的软件和硬件设备&#xff0c;在计算机网络的内、外网之间构建一道相对隔绝的保护屏障&#xff0c;以保护用户资料与信息的安全性。 防火墙的作用的详细说明&#xff1a; 1.访问控制&#xff1a;防火…

SpingBoot的项目实战--模拟电商【2.登录】

&#x1f973;&#x1f973;Welcome Huihuis Code World ! !&#x1f973;&#x1f973; 接下来看看由辉辉所写的关于SpringBoot电商项目的相关操作吧 目录 &#x1f973;&#x1f973;Welcome Huihuis Code World ! !&#x1f973;&#x1f973; 一.功能需求 二.代码编写 …

如何使用mac电脑,1、使用快捷命令打开访达,2、使用终端命令创建文件,3、使用命令打开创建的文件,并且在vscode中打开

如何使用mac电脑 1、使用快捷命令打开访达 optioncommand空格键 快速进入访达 shiftcmmandn 创建一个空目录 2、使用终端命令创建文件 2.1进入文件夹 在终端页面输入“cd /Users/yunf/Desktop/”并按回车键&#xff08;此时进入到桌面文件夹&#xff0c;如果需要进入到其它…

算法分析-回溯算法-求解N皇后问题

一.题目需求 n皇后问题是一道比较经典的算法题。它研究的是将n个皇后放置在一个nn的棋盘上&#xff0c;使皇后彼此之间不相互攻击。 即任意两个皇后都不能处于同一行、同一列或同一斜线上。 二.算法思想 1.构建棋盘 可以用一个nn列表来表示棋盘&#xff0c;设皇后所在的位…

Vue 问题解决

一、问题&#xff1a;TypeError: (0 , _message.default) is not a function 当没有default时,在其他页面import引入的时&#xff0c;必须加{}。 二、问题&#xff1a;Vue前端页面的表格数据总是一行一行的显示 使用Async/Await来解决前端数据一行一行显示的问题。可以将获取部…

vue+element+springboot实现多张图片上传

1.需求说明 2.实现思路 3.el-upload组件主要属性说明 4.前端传递MultipartFile数组与服务端接收说明 5.完整代码 1.需求说明 动态模块新增添加动态功能,支持多张图片上传.实现过程中对el-upload组件不是很熟悉,踩了很多坑,当然也参考过别的文章,发现处理很…

Spark RDD操作性能优化技巧

Apache Spark是一个强大的分布式计算框架&#xff0c;用于处理大规模数据。然而&#xff0c;在处理大数据集时&#xff0c;性能优化成为一个关键问题。本文将介绍一些Spark RDD操作的性能优化技巧&#xff0c;帮助大家充分利用Spark的潜力&#xff0c;并获得更快的处理速度。 …

2023.12.27 关于 Redis 数据类型 List 常用命令

目录 List 类型基本概念 List 类型特点 List 操作命令 LPUSH LPUSHX RPUSH RPUSHX LRANGE LPOP RPOP LINDEX LINSERT LREM LTRIM LSET 阻塞版本的命令 阻塞版本 和 非阻塞版本的区别 BLPOP & BRPOP List 类型基本概念 Redis 中的列表&#xff08;list&am…

第十一章 Stream消息驱动

Stream消息驱动 gitee:springcloud_study: springcloud&#xff1a;服务集群、注册中心、配置中心&#xff08;热更新&#xff09;、服务网关&#xff08;校验、路由、负载均衡&#xff09;、分布式缓存、分布式搜索、消息队列&#xff08;异步通信&#xff09;、数据库集群、…

Apache Commons JCS缓存解决方案

第1章&#xff1a;引言 大家好&#xff0c;我是小黑&#xff01;今天&#xff0c;咱们来聊聊Apache Commons JCS&#xff0c;一个Java界里的缓存大杀器。缓存技术&#xff0c;对于提高应用性能来说&#xff0c;就像是给它加了一剂兴奋剂&#xff0c;能让数据访问变得快如闪电。…