1. TemplatePart vs. VisualState

在前面两篇文章中分别使用了TemplatePart及VisualState的方式实现了相同的功能,其中明显VisualState的方式更灵活一些。如果遇到这种情况通常我更倾向使用VisualState。不过在实际应用中这两种实现方式并不是互斥的,很多模板化控件都同时使用这两种方式,

使用VisualState有如下好处:

  • 代码和UI分离。
  • 可以更灵活地扩展控件。
  • 可以使用Blend轻松实现动画。

并不是说VisualState好处这么多就一定要用VisualState实现所有功能,下面这些情况我会选择使用TemplatePart:

  • 需要快速实现一个控件。
  • 某个行为时固定的,不需要扩展。
  • 需要在代码中操作UI,譬如Slider或ComboBox。
  • 为了强调某个部件是控件必须的。
  • 为了隐藏实现细节,限制派生类或ControlTemplate修改重要的逻辑。

其中,使用TemplatePart产生的扩展性问题是我谨慎使用这种方案的最大因素。

2. TemplatePart vs. TemplateBinding

除了VisualState,TemplatePart的功能也常常会被TemplateBinding代替。前面的例子展示了使用VisualState在UI上的优势,这次用另一个控件DateTimeSelector来讨论使用TemplatePart在扩展性上的其它问题。

2.1 使用TemplatePart

DateTimeSelector组合了CalendarDatePicker和TimePicker,用于选择日期和时间(SelectedDateTime)。它的XAML如下:

<Style TargetType="local:DateTimeSelector">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:DateTimeSelector">
<StackPanel Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<CalendarDatePicker x:Name="DateElement"
Margin="0,0,0,5" />
<TimePicker x:Name="TimeElement" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

代码如下:

[TemplatePart(Name = DateElementPartName, Type = typeof(CalendarDatePicker))]
[TemplatePart(Name = TimeElementPartName, Type = typeof(TimePicker))]
public class DateTimeSelector : Control
{
public const string DateElementPartName = "DateElement";
public const string TimeElementPartName = "TimeElement"; /// <summary>
/// 标识 SelectedDateTime 依赖属性。
/// </summary>
public static readonly DependencyProperty SelectedDateTimeProperty =
DependencyProperty.Register("SelectedDateTime", typeof(DateTime), typeof(DateTimeSelector), new PropertyMetadata(DateTime.Now, OnSelectedDateTimeChanged)); private static void OnSelectedDateTimeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DateTimeSelector target = obj as DateTimeSelector;
DateTime oldValue = (DateTime)args.OldValue;
DateTime newValue = (DateTime)args.NewValue;
if (oldValue != newValue)
target.OnSelectedDateTimeChanged(oldValue, newValue);
} public DateTimeSelector()
{
this.DefaultStyleKey = typeof(DateTimeSelector);
} /// <summary>
/// 获取或设置SelectedDateTime的值
/// </summary>
public DateTime SelectedDateTime
{
get { return (DateTime)GetValue(SelectedDateTimeProperty); }
set { SetValue(SelectedDateTimeProperty, value); }
} private CalendarDatePicker _dateElement;
private TimePicker _timeElement;
private bool _isUpdatingDateTime; protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (_dateElement != null)
_dateElement.DateChanged -= OnDateElementDateChanged; _dateElement = GetTemplateChild(DateElementPartName) as CalendarDatePicker;
if (_dateElement != null)
_dateElement.DateChanged += OnDateElementDateChanged; if (_timeElement != null)
_timeElement.TimeChanged -= OnTimeElementTimeChanged; _timeElement = GetTemplateChild(TimeElementPartName) as TimePicker;
if (_timeElement != null)
_timeElement.TimeChanged += OnTimeElementTimeChanged; UpdateElement();
} protected virtual void OnSelectedDateTimeChanged(DateTime oldValue, DateTime newValue)
{
UpdateElement();
} private void OnDateElementDateChanged(CalendarDatePicker sender, CalendarDatePickerDateChangedEventArgs args)
{
UpdateSelectDateTime();
} private void OnTimeElementTimeChanged(object sender, TimePickerValueChangedEventArgs e)
{
UpdateSelectDateTime();
} private void UpdateElement()
{
_isUpdatingDateTime = true;
try
{
if (_dateElement != null)
_dateElement.Date = SelectedDateTime.Date; if (_timeElement != null)
_timeElement.Time = SelectedDateTime.TimeOfDay;
}
finally
{
_isUpdatingDateTime = false;
}
} private void UpdateSelectDateTime()
{
if (_isUpdatingDateTime)
return; DateTime dateTime = DateTime.Now;
if (_dateElement != null && _dateElement.Date.HasValue)
dateTime = _dateElement.Date.Value.Date; if (_timeElement != null)
dateTime = dateTime.Add(_timeElement.Time); SelectedDateTime = dateTime;
}
}

可以看出,DateTimeSelector通过监视CalendarDatePicker的DateChanged和TimePicker的TimeChanged来改变SelectedDateTime的值。

DateTimeSelector的代码很简单,控件也工作得很好,但如果某天需要将CalendarDatePicker 替换为DatePicker或某个第三方的日期选择控件,DateTimeSelector就无能为力了,既不能通过修改ControlTemplate,也不能通过继承来达到目的。

2.2. 使用TemplateBinding

通常在构建这类控件时应先考虑它的数据和行为,而不关心它的UI。DateTimeSelector最核心的功能是通过选择Date和Time得出组合起来的DateTime,那么就可以先写出如下的类:

public class DateTimeSelector2 : Control
{
/// <summary>
/// 标识 Date 依赖属性。
/// </summary>
public static readonly DependencyProperty DateProperty =
DependencyProperty.Register("Date", typeof(DateTime), typeof(DateTimeSelector2), new PropertyMetadata(DateTime.Now, OnDateChanged)); private static void OnDateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DateTimeSelector2 target = obj as DateTimeSelector2;
DateTime oldValue = (DateTime)args.OldValue;
DateTime newValue = (DateTime)args.NewValue;
if (oldValue != newValue)
target.OnDateChanged(oldValue, newValue);
} /// <summary>
/// 标识 Time 依赖属性。
/// </summary>
public static readonly DependencyProperty TimeProperty =
DependencyProperty.Register("Time", typeof(TimeSpan), typeof(DateTimeSelector2), new PropertyMetadata(TimeSpan.Zero, OnTimeChanged)); private static void OnTimeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DateTimeSelector2 target = obj as DateTimeSelector2;
TimeSpan oldValue = (TimeSpan)args.OldValue;
TimeSpan newValue = (TimeSpan)args.NewValue;
if (oldValue != newValue)
target.OnTimeChanged(oldValue, newValue);
} /// <summary>
/// 标识 DateTime 依赖属性。
/// </summary>
public static readonly DependencyProperty DateTimeProperty =
DependencyProperty.Register("DateTime", typeof(DateTime), typeof(DateTimeSelector2), new PropertyMetadata(DateTime.Now, OnDateTimeChanged)); private static void OnDateTimeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DateTimeSelector2 target = obj as DateTimeSelector2;
DateTime oldValue = (DateTime)args.OldValue;
DateTime newValue = (DateTime)args.NewValue;
if (oldValue != newValue)
target.OnDateTimeChanged(oldValue, newValue);
} public DateTimeSelector2()
{
this.DefaultStyleKey = typeof(DateTimeSelector2);
} /// <summary>
/// 获取或设置Date的值
/// </summary>
public DateTime Date
{
get { return (DateTime)GetValue(DateProperty); }
set { SetValue(DateProperty, value); }
} /// <summary>
/// 获取或设置Time的值
/// </summary>
public TimeSpan Time
{
get { return (TimeSpan)GetValue(TimeProperty); }
set { SetValue(TimeProperty, value); }
} /// <summary>
/// 获取或设置DateTime的值
/// </summary>
public DateTime DateTime
{
get { return (DateTime)GetValue(DateTimeProperty); }
set { SetValue(DateTimeProperty, value); }
} private bool _isUpdatingDateTime; protected virtual void OnDateChanged(DateTime oldValue, DateTime newValue)
{
UpdateDateTime();
} protected virtual void OnTimeChanged(TimeSpan oldValue, TimeSpan newValue)
{
UpdateDateTime();
} protected virtual void OnDateTimeChanged(DateTime oldValue, DateTime newValue)
{
_isUpdatingDateTime = true;
try
{
Date = newValue.Date;
Time = newValue.TimeOfDay;
}
finally
{
_isUpdatingDateTime = false;
}
} private void UpdateDateTime()
{
if (_isUpdatingDateTime)
return; DateTime = Date.Date.Add(Time);
}
}

控件的代码并不清楚ControlTemplate中包含什么控件,它只关心自己的数据。

XAML中通过绑定使用这些数据。

<Style TargetType="local:DateTimeSelector2">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:DateTimeSelector2">
<StackPanel Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<CalendarDatePicker Margin="0,0,0,5"
Date="{Binding Date,RelativeSource={RelativeSource Mode=TemplatedParent},Mode=TwoWay,Converter={StaticResource DateTimeOffsetConverter}}" />
<TimePicker Time="{Binding Time,RelativeSource={RelativeSource Mode=TemplatedParent},Mode=TwoWay}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style> <Style x:Key="DateTimeSelector2CustomStyle"
TargetType="local:DateTimeSelector2">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:DateTimeSelector2">
<StackPanel Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<DatePicker Margin="0,0,0,5"
Date="{Binding Date,RelativeSource={RelativeSource Mode=TemplatedParent},Mode=TwoWay,Converter={StaticResource DateTimeOffsetConverter}}" />
<TimePicker Time="{Binding Time,RelativeSource={RelativeSource Mode=TemplatedParent},Mode=TwoWay}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

这里给出了两个Style,分别使用了CalendarDatePicker 和DatePicker ,通过TwoWay Binding访问DateTimeSelector2中的Date属性。如果你的TemplatedControl需要有良好的扩展能力,可以尝试使用这种方式。

[UWP 自定义控件]了解模板化控件(5.1):TemplatePart vs. VisualState的更多相关文章

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

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

  2. UWP 自定义控件:了解模板化控件 系列文章

    UWP自定义控件的入门文章 [UWP 自定义控件]了解模板化控件(1):基础知识 [UWP 自定义控件]了解模板化控件(2):模仿ContentControl [UWP 自定义控件]了解模板化控件(2 ...

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

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

  4. [UWP 自定义控件]了解模板化控件(8):ItemsControl

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

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

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

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

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

  7. [UWP 自定义控件]了解模板化控件(3):实现HeaderedContentControl

    1. 概述 来看看这段XMAL: <StackPanel Width="300"> <TextBox Header="TextBox" /&g ...

  8. [UWP 自定义控件]了解模板化控件(5):VisualState

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

  9. [UWP 自定义控件]了解模板化控件(5.2):UserControl vs. TemplatedControl

    1. UserControl vs. TemplatedControl 在UWP中自定义控件常常会遇到这个问题:使用UserControl还是TemplatedControl来自定义控件. 1.1 使 ...

随机推荐

  1. [20180319]直接路径读特例12c.txt

    [20180319]直接路径读特例12c.txt --//昨天的测试突然想起以前遇到的直接路径读特例,在12c重复测试看看. 1.环境:SCOTT@test01p> @ ver1 PORT_ST ...

  2. [20170703]从备份集取出spfile转化为pfile.txt

    [20170703]从备份集取出spfile转化为pfile.txt --//上个星期的事情,要从备份集里面取出看看spfile文件某个参数当时的情况,结果尝试命令老是出错,做一个记录.--//最后选 ...

  3. 洗礼灵魂,修炼python(9)--灵性的字符串

    python几大核心之——字符串 1.什么是字符串 其实前面说到数据类型时说过了,就是带有引号的参数,“”引号内的一切东西就是字符串,字符串又叫文本. 2.创建字符串的两种方式: 3.字符串的方法: ...

  4. Install Google Chrome on Fedora 28/27, CentOS/RHEL 7.5 (在 fedora 28 等 上 安装 chrome)

    今天在使用 fedora 安装 chrome 的时候遇到了问题,今天进行将安装过程进行记录下来.需要安装第三方软件仓库. 我们需要进行安装 fedora-workstation-repositorie ...

  5. Oracle SQL: DDL DML DCL TCL

    Data Definition Language 自带commit,与表结构有关(数据字典)(会等待对象锁) Data Manipulation Language (数据文件相关变化有关,会产生锁)不 ...

  6. C# show和showdialog区别

    简单地说他们的区别就是show弹出来的窗体和父窗体(上一个窗体的简称)是属于同一等级的,这两个窗体可以同时存在而且可以随意切换,但是showdialog弹出来的窗体就不能这样,他永远是被置顶的,如果不 ...

  7. el-table-column v-if条件渲染报错h.$scopedSlots.default is not a function

    我们在实际项目中经常会遇到el-table-column条件渲染出现报错的情况 报错内容: h.$scopedSlots.default is not a function 究其原因,是因为表格是el ...

  8. jeDate 日期控件

    写在前面的话: 最近在做一个日期范围的功能,研究了一个12306网站的日期范围选择,他用的是jcalendar.js,没有直接在日历插件里面做判断开始时间小于结束时间 而是自己在代码里面做了判断如下: ...

  9. Python3.6安装及引入Requests库

    本博客可能没有那么规范,环境之类的配置.只是让你直接开始编程写python. 至于各种配置网络上有多种方法. 本文仅代表我的观点的一种方法. 电脑环境:win10 64位 第一步:下载python. ...

  10. 【洛谷】【最小生成树】P1536 村村通

    [题目描述:] 某市调查城镇交通状况,得到现有城镇道路统计表.表中列出了每条道路直接连通的城镇.市政府"村村通工程"的目标是使全市任何两个城镇间都可以实现交通(但不一定有直接的道路 ...