1. 概述

来看看这段XMAL:

<StackPanel Width="300">
<TextBox Header="TextBox" />
<ComboBox Header="ComboBox" HorizontalAlignment="Stretch"/>
<AutoSuggestBox Header="AutoSuggestBox" />
<TextBlock Text="ListBox" />
<ListBox>
<ListBoxItem Content="ListBoxItem 1" />
<ListBoxItem Content="ListBoxItem 2" />
<ListBoxItem Content="ListBoxItem 3" />
</ListBox>
</StackPanel>

是不是觉得它们中出了一个叛徒?这个示例中除了ListBox控件其它都自带Header,但是ListBox没有Header属性,只好用一个TextBlock模仿它的Header。这样就带来一个问题:只有ListBox的Header高度和其它控件不一致。

既然现在讨论的是自定义控件,这里就用自定义控件的方式解决这个问题。首先想到最简单的方法,就是自定义一个HeaderedContentControl,如名字所示,这个控件继承自ContentControl并拥有Header属性,用起来大概是这样:

<HeaderedContentControl Header="ListBox">
<ListBox/>
</HeaderedContentControl>

这样,只要在HeaderedContentControl的样式中模仿其它含Header属性的控件,就能统一Header的外观。

WPF中本来就有这个控件,它是Expander、GroupBox、TabItem等诸多拥有Header属性的控件的基类,十分方便好用。UWP中模仿这个控件很简单,而且很适合用来学习自定义控件的进阶知识。

2. 定义HeaderedContentControl结构

比起WPF,借鉴Silverlight的HeaderedContentControl比较好,因为Silverlight的比较简单。HeaderedContentControl只需要在继承ContentControl后添加两个属性:Header和HeaderTemplate。

public class HeaderedContentControl : ContentControl
{
public HeaderedContentControl()
{
this.DefaultStyleKey = typeof(HeaderedContentControl);
} /// <summary>
/// 获取或设置Header的值
/// </summary>
public object Header
{
get { return (object)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
} /// <summary>
/// 标识 Header 依赖属性。
/// </summary>
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(object), typeof(HeaderedContentControl), new PropertyMetadata(null, OnHeaderChanged)); private static void OnHeaderChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
HeaderedContentControl target = obj as HeaderedContentControl;
object oldValue = (object)args.OldValue;
object newValue = (object)args.NewValue;
if (oldValue != newValue)
target.OnHeaderChanged(oldValue, newValue);
} /// <summary>
/// 获取或设置HeaderTemplate的值
/// </summary>
public DataTemplate HeaderTemplate
{
get { return (DataTemplate)GetValue(HeaderTemplateProperty); }
set { SetValue(HeaderTemplateProperty, value); }
} /// <summary>
/// 标识 HeaderTemplate 依赖属性。
/// </summary>
public static readonly DependencyProperty HeaderTemplateProperty =
DependencyProperty.Register("HeaderTemplate", typeof(DataTemplate), typeof(HeaderedContentControl), new PropertyMetadata(null, OnHeaderTemplateChanged)); private static void OnHeaderTemplateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
HeaderedContentControl target = obj as HeaderedContentControl;
DataTemplate oldValue = (DataTemplate)args.OldValue;
DataTemplate newValue = (DataTemplate)args.NewValue;
if (oldValue != newValue)
target.OnHeaderTemplateChanged(oldValue, newValue);
} protected virtual void OnHeaderChanged(object oldValue, object newValue)
{
} protected virtual void OnHeaderTemplateChanged(DataTemplate oldValue, DataTemplate newValue)
{
}
}

3. 设计样式

在C:\Program Files (x86)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP\10.0.14393.0\Generic\generic.xaml中找到ContentControl的样式。

再从TextBox的Style中找到HeaderContentPresenter

提示: 随便找个有ThemeResource的XAML,譬如Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}",在资源名称(ApplicationPageBackgroundThemeBrush)上按"F12",即可导航到存放ThemeResource的generic.xaml。

组合起来,HeaderedContentControl的默认样式就完成了。

<Style TargetType="local:HeaderedContentControl">
<Setter Property="HorizontalContentAlignment"
Value="Left" />
<Setter Property="VerticalContentAlignment"
Value="Top" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:HeaderedContentControl">
<StackPanel>
<ContentPresenter x:Name="HeaderContentPresenter"
Foreground="{ThemeResource TextControlHeaderForeground}"
Margin="0,0,0,8"
Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}"
FontWeight="Normal" />
<ContentPresenter Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Margin="{TemplateBinding Padding}"
ContentTransitions="{TemplateBinding ContentTransitions}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

4. 使用

 <StackPanel Visibility="Collapsed">
<TextBox Header="TextBox" />
<ComboBox Header="ComboBox"
HorizontalAlignment="Stretch" />
<AutoSuggestBox Header="AutoSuggestBox" />
<local:HeaderedContentControl Header="ListBox">
<ListBox>
<ListBoxItem Content="ListBoxItem 1" />
<ListBoxItem Content="ListBoxItem 2" />
<ListBoxItem Content="ListBoxItem 3" />
</ListBox>
</local:HeaderedContentControl>
</StackPanel>

调用代码及效果。这样外观就统一了。

注意: 我移除了 x:DeferLoadStrategy="Lazy"这句,这个知识点比较适合放在有关性能的主题里讨论。

[UWP]了解模板化控件(3):实现HeaderedContentControl的更多相关文章

  1. [UWP]了解模板化控件(4):TemplatePart

    1. TemplatePart TemplatePart(部件)是指ControlTemplate中的命名元素.控件逻辑预期这些部分存在于ControlTemplate中,并且使用protected ...

  2. [UWP]了解模板化控件(8):ItemsControl

    1. 模仿ItemsControl 顾名思义,ItemsControl是展示一组数据的控件,它是UWP UI系统中最重要的控件之一,和展示单一数据的ContentControl构成了UWP UI的绝大 ...

  3. [UWP]了解模板化控件(9):UI指南

    1. 使用TemplateSettings统一外观 TemplateSettings提供一组只读属性,用于在新建ControlTemplate时使用这些约定的属性. 譬如,修改HeaderedCont ...

  4. [UWP]合体姿势不对的HeaderedContentControl

    1. 前言 HeaderedContentControl是WPF中就存在的控件,这个控件的功能很简单:提供Header和Content两个属性,在UI上创建两个ContentPresenter并分别绑 ...

  5. [UWP]了解模板化控件(1):基础知识

    1.概述 UWP允许开发者通过两种方式创建自定义的控件:UserControl和TemplatedControl(模板化控件).这个主题主要讲述如何创建和理解模板化控件,目标是能理解模板化控件常见的知 ...

  6. [UWP]了解模板化控件(2):模仿ContentControl

    ContentControl是最简单的TemplatedControl,而且它在UWP出场频率很高.ContentControl和Panel是VisualTree的基础,可以说几乎所有VisualTr ...

  7. [UWP]了解模板化控件(5):VisualState

    1. 功能需求 使用TemplatePart实现上篇文章的两个需求(Header为空时隐藏HeaderContentPresenter,鼠标没有放在控件上时HeaderContentPresent半透 ...

  8. [UWP]了解模板化控件(10):原则与技巧

    1. 原则 推荐以符合以下原则的方式编写模板化控件: 选择合适的父类:选择合适的父类可以节省大量的工作,从UWP自带的控件中选择父类是最安全的做法,通常的选择是Control.ContentContr ...

  9. [UWP]了解模板化控件(2.1):理解ContentControl

    UWP的UI主要由布局容器和内容控件(ContentControl)组成.布局容器是指Grid.StackPanel等继承自Panel,可以拥有多个子元素的类.与此相对,ContentControl则 ...

随机推荐

  1. bppm与AD域集成

    1. 使用admin登录BMC ProactiveNet Operations Console,点击选项-> 集成编辑 2. 勾选LDAP集成方式,配置相关信息,点击应用 3. 查看配置文件%B ...

  2. 【吐血整理】SVN命令行,Subversion的正确使用姿势,让版本控制更简单~

    一.写在前面 前面一直博主一直用svn的桌面版本,但看项目经理一直都用的命令行方式,不为性能,还能直接装逼呀!在这里先感谢赵哥,也把它分享给感兴趣的你们~ 二.直接上干货 1. svn checkou ...

  3. Java Web(二) Servlet中response、request乱码问题解决

    三月不减肥,五月徒伤悲,这就是我现在的状态,哈哈~ 健身.博客坚持. --WH 一.request请求参数出现的乱码问题 get请求: get请求的参数是在url后面提交过来的,也就是在请求行中, M ...

  4. checkinstall包的使用

    1. Checkinstall是个很有用的工具.当软件编译过后,Checkinstall能够帮助安装. 下面的命令是安装软件 ./configure make make install 但是用这种安装 ...

  5. jQuery中绑定事件bind() on() live() one()的异同

    jQuery中绑定事件的四种方法,他们可以同时绑定一个或多个事件 bind()-------------------------版本号小于3.0(在Jquery3.0中已经移除,相应unbind()也 ...

  6. Java回调机制解读

    模块间调用 在一个应用系统中,无论使用何种语言开发,必然存在模块之间的调用,调用的方式分为几种: (1)同步调用 同步调用是最基本并且最简单的一种调用方式,类A的方法a()调用类B的方法b(),一直等 ...

  7. 基于vue2.0+vuex+localStorage开发的本地记事本

    本文采用vue2.0+vuex+localStorage+sass+webpack,实现一个本地存储的记事本.兼容PC端和移动端.在线预览地址:DEMO github地址:https://github ...

  8. window编程之win程序框架

    int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmd ...

  9. 使用grunt完成requirejs的合并压缩和js文件的版本控制

    最近有一个项目使用了 requirejs 来解决前端的模块化,但是随着页面和模块的越来越多,我发现我快要hold不住这些可爱的js文件了,具体表现在每个页面都要设置一堆 requirejs 的配置( ...

  10. 在Azure上部署带有GPU的深度学习虚拟机

    1. 登录https://portal.azure.com 2. 点击"+创建",在弹出的页面搜索"deep learning toolkit for the DSVM& ...