[UWP]了解模板化控件(6):使用附加属性
1. 基本需求
之前的ContentView2添加了PointerOver等效果,和TextBox等本来就有Header的控件放在一起反而变得鹤立鸡群。
为了解决这个问题,这次把ContentView2的Header部分分离出来做成一个可复用的控件HeaderView,它继承自Control,并且拥有Header属性及AttachElement属性。把它放到其他控件的ControlTemplate替换原本的HeaderContentPresenter,这样就能统一外观了。在ControlTemplate中它的使用方式如下:
<local:HeaderView AttachedElement="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}}"
Header="{TemplateBinding Header}" />
AttachedElement使用Mode=TemplatedParent的绑定,获取模板所属的控件。在HeaderView的代码中监视AttachedElement值的改变,并订阅AttachedElement的PointerEntered 和PointerExited 事件,改变VisualState:
protected virtual void OnAttachedElementChanged(FrameworkElement oldValue, FrameworkElement newValue)
{
if (oldValue != null)
{
oldValue.PointerEntered -= OnPointerEntered;
oldValue.PointerExited -= OnPointerExited;
}
if (newValue != null)
{
newValue.PointerEntered += OnPointerEntered;
newValue.PointerExited += OnPointerExited;
}
}
private void OnPointerEntered(object sender, PointerRoutedEventArgs e)
{
_isPointerEntered = true;
UpdateVisualState();
}
private void OnPointerExited(object sender, PointerRoutedEventArgs e)
{
_isPointerEntered = false;
UpdateVisualState();
}
这样基本的功能就实现了。
2. 使用附加属性
如果要为所有含有Header属性的控件修改ControlTemplate,这将是一个很麻烦的工作。为了避免重复性工作,可以尝试用附加属性解决。
为HeaderView添加一个ExtendHeader附加属性,并且在PropertyChangedCallback函数中检查所附加的对象有没有Header属性,如果有,将Header值设置到一个全新的HeaderView对象的Header,并且将所附加的控件的Header改为这个HeaderView对象。描述起来比较绕口,看代码更直观些:
/// <summary>
// 从指定元素获取 ExtendHeader 依赖项属性的值。
/// </summary>
/// <param name="obj">The element from which the property value is read.</param>
/// <returns>ExtendHeader 依赖项属性的值</returns>
public static object GetExtendHeader(DependencyObject obj)
{
return (object)obj.GetValue(ExtendHeaderProperty);
}
/// <summary>
/// 将 ExtendHeader 依赖项属性的值设置为指定元素。
/// </summary>
/// <param name="obj">The element on which to set the property value.</param>
/// <param name="value">The property value to set.</param>
public static void SetExtendHeader(DependencyObject obj, object value)
{
obj.SetValue(ExtendHeaderProperty, value);
}
/// <summary>
/// 标识 ExtendHeader 依赖项属性。
/// </summary>
public static readonly DependencyProperty ExtendHeaderProperty =
DependencyProperty.RegisterAttached("ExtendHeader", typeof(object), typeof(HeaderView), new PropertyMetadata(0, OnExtendHeaderChanged));
private static void OnExtendHeaderChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
HeaderView target = obj as HeaderView;
object oldValue = (object)args.OldValue;
object newValue = (object)args.NewValue;
if (oldValue == newValue)
return;
FrameworkElement element = obj as FrameworkElement;
if (element == null)
return;
var headerProperty = element.GetType().GetProperty("Header");
if (headerProperty == null)
return;
HeaderView view = new HeaderView
{
Header = newValue,
AttachedElement = element
};
headerProperty.SetValue(element, view);
}
在XAML中使用如下:
<TextBox local:HeaderView.ExtendHeader="TextBox Header"
PlaceholderText="Input some text..." />
在ControlTemplate中也可以用到这个附加属性。例如ListBox没有Header属性,ListBox中的ControlTemplate中的HeaderView可以绑定到HeaderView.ExtendHeader。
<ListBox local:HeaderView.ExtendHeader="ListBox Header">
<ListBox.Template>
<ControlTemplate TargetType="ListBox">
<Border x:Name="LayoutRoot"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel>
<local:HeaderView AttachedElement="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}}"
Header="{TemplateBinding local:HeaderView.ExtendHeader}" />
<ScrollViewer x:Name="ScrollViewer"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
TabNavigation="{TemplateBinding TabNavigation}"
HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}"
IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}"
AutomationProperties.AccessibilityView="Raw">
<ItemsPresenter />
</ScrollViewer>
</StackPanel>
</Border>
</ControlTemplate>
</ListBox.Template>
<ListBoxItem Content="ListBoxItem 1" />
<ListBoxItem Content="ListBoxItem 2" />
<ListBoxItem Content="ListBoxItem 3" />
</ListBox>
3. 完整的代码:
[TemplateVisualState(Name = NormalState, GroupName = CommonStates)]
[TemplateVisualState(Name = PointerOverState, GroupName = CommonStates)]
[TemplateVisualState(Name = NoHeaderState, GroupName = HeaderStates)]
[TemplateVisualState(Name = HasHeaderState, GroupName = HeaderStates)]
public class HeaderView : Control
{
public const string CommonStates = "CommonStates";
public const string NormalState = "Normal";
public const string PointerOverState = "PointerOver";
public const string HeaderStates = "HeaderStates";
public const string NoHeaderState = "NoHeader";
public const string HasHeaderState = "HasHeader";
/// <summary>
// 从指定元素获取 ExtendHeader 依赖项属性的值。
/// </summary>
/// <param name="obj">The element from which the property value is read.</param>
/// <returns>ExtendHeader 依赖项属性的值</returns>
public static object GetExtendHeader(DependencyObject obj)
{
return (object)obj.GetValue(ExtendHeaderProperty);
}
/// <summary>
/// 将 ExtendHeader 依赖项属性的值设置为指定元素。
/// </summary>
/// <param name="obj">The element on which to set the property value.</param>
/// <param name="value">The property value to set.</param>
public static void SetExtendHeader(DependencyObject obj, object value)
{
obj.SetValue(ExtendHeaderProperty, value);
}
/// <summary>
/// 标识 ExtendHeader 依赖项属性。
/// </summary>
public static readonly DependencyProperty ExtendHeaderProperty =
DependencyProperty.RegisterAttached("ExtendHeader", typeof(object), typeof(HeaderView), new PropertyMetadata(0, OnExtendHeaderChanged));
private static void OnExtendHeaderChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
HeaderView target = obj as HeaderView;
object oldValue = (object)args.OldValue;
object newValue = (object)args.NewValue;
if (oldValue == newValue)
return;
FrameworkElement element = obj as FrameworkElement;
if (element == null)
return;
var headerProperty = element.GetType().GetProperty("Header");
if (headerProperty == null)
return;
HeaderView view = new HeaderView
{
Header = newValue,
AttachedElement = element
};
headerProperty.SetValue(element, view);
}
/// <summary>
// 从指定元素获取 Header 依赖项属性的值。
/// </summary>
/// <param name="obj">The element from which the property value is read.</param>
/// <returns>Header 依赖项属性的值</returns>
public static object GetHeader(DependencyObject obj)
{
return (object)obj.GetValue(HeaderProperty);
}
/// <summary>
/// 将 Header 依赖项属性的值设置为指定元素。
/// </summary>
/// <param name="obj">The element on which to set the property value.</param>
/// <param name="value">The property value to set.</param>
public static void SetHeader(DependencyObject obj, object value)
{
obj.SetValue(HeaderProperty, value);
}
/// <summary>
/// 标识 Header 依赖属性。
/// </summary>
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(object), typeof(HeaderView), new PropertyMetadata(null, OnHeaderChanged));
private static void OnHeaderChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
object oldValue = (object)args.OldValue;
object newValue = (object)args.NewValue;
if (oldValue == newValue)
return;
HeaderView target = obj as HeaderView;
if (target != null)
{
target.OnHeaderChanged(oldValue, newValue);
}
}
/// <summary>
/// 标识 AttachedElement 依赖属性。
/// </summary>
public static readonly DependencyProperty AttachedElementProperty =
DependencyProperty.Register("AttachedElement", typeof(FrameworkElement), typeof(HeaderView), new PropertyMetadata(null, OnAttachedElementChanged));
private static void OnAttachedElementChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
HeaderView target = obj as HeaderView;
FrameworkElement oldValue = (FrameworkElement)args.OldValue;
FrameworkElement newValue = (FrameworkElement)args.NewValue;
if (oldValue != newValue)
target.OnAttachedElementChanged(oldValue, newValue);
}
public HeaderView()
{
this.DefaultStyleKey = typeof(HeaderView);
}
/// <summary>
/// 获取或设置Header的值
/// </summary>
public object Header
{
get { return (object)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
/// <summary>
/// 获取或设置AttachedElement的值
/// </summary>
public FrameworkElement AttachedElement
{
get { return (FrameworkElement)GetValue(AttachedElementProperty); }
set { SetValue(AttachedElementProperty, value); }
}
private bool _isPointerEntered;
protected virtual void OnAttachedElementChanged(FrameworkElement oldValue, FrameworkElement newValue)
{
if (oldValue != null)
{
oldValue.PointerEntered -= OnPointerEntered;
oldValue.PointerExited -= OnPointerExited;
}
if (newValue != null)
{
newValue.PointerEntered += OnPointerEntered;
newValue.PointerExited += OnPointerExited;
}
}
protected virtual void OnHeaderChanged(object oldValue, object newValue)
{
UpdateVisualState();
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
UpdateVisualState(false);
}
private void OnPointerEntered(object sender, PointerRoutedEventArgs e)
{
_isPointerEntered = true;
UpdateVisualState();
}
private void OnPointerExited(object sender, PointerRoutedEventArgs e)
{
_isPointerEntered = false;
UpdateVisualState();
}
internal virtual void UpdateVisualState(bool useTransitions = true)
{
if (_isPointerEntered)
VisualStateManager.GoToState(this, PointerOverState, useTransitions);
else
VisualStateManager.GoToState(this, NormalState, useTransitions);
if (Header == null)
VisualStateManager.GoToState(this, NoHeaderState, useTransitions);
else
VisualStateManager.GoToState(this, HasHeaderState, useTransitions);
}
}
[UWP]了解模板化控件(6):使用附加属性的更多相关文章
- [UWP]了解模板化控件(1):基础知识
1.概述 UWP允许开发者通过两种方式创建自定义的控件:UserControl和TemplatedControl(模板化控件).这个主题主要讲述如何创建和理解模板化控件,目标是能理解模板化控件常见的知 ...
- [UWP]了解模板化控件(9):UI指南
1. 使用TemplateSettings统一外观 TemplateSettings提供一组只读属性,用于在新建ControlTemplate时使用这些约定的属性. 譬如,修改HeaderedCont ...
- [UWP]了解模板化控件(2):模仿ContentControl
ContentControl是最简单的TemplatedControl,而且它在UWP出场频率很高.ContentControl和Panel是VisualTree的基础,可以说几乎所有VisualTr ...
- [UWP]了解模板化控件(4):TemplatePart
1. TemplatePart TemplatePart(部件)是指ControlTemplate中的命名元素.控件逻辑预期这些部分存在于ControlTemplate中,并且使用protected ...
- [UWP]了解模板化控件(5):VisualState
1. 功能需求 使用TemplatePart实现上篇文章的两个需求(Header为空时隐藏HeaderContentPresenter,鼠标没有放在控件上时HeaderContentPresent半透 ...
- [UWP]了解模板化控件(8):ItemsControl
1. 模仿ItemsControl 顾名思义,ItemsControl是展示一组数据的控件,它是UWP UI系统中最重要的控件之一,和展示单一数据的ContentControl构成了UWP UI的绝大 ...
- [UWP]了解模板化控件(10):原则与技巧
1. 原则 推荐以符合以下原则的方式编写模板化控件: 选择合适的父类:选择合适的父类可以节省大量的工作,从UWP自带的控件中选择父类是最安全的做法,通常的选择是Control.ContentContr ...
- [UWP]了解模板化控件(2.1):理解ContentControl
UWP的UI主要由布局容器和内容控件(ContentControl)组成.布局容器是指Grid.StackPanel等继承自Panel,可以拥有多个子元素的类.与此相对,ContentControl则 ...
- [UWP]了解模板化控件(3):实现HeaderedContentControl
1. 概述 来看看这段XMAL: <StackPanel Width="300"> <TextBox Header="TextBox" /&g ...
随机推荐
- 使用Docker跑MySQL 作为Django的存储后端
Docker的好处不科普了,用过的都说好. 不想污染自己开发机器上的文件环境,本萌新使用Docker运行Mysql,Redis来作为Django的存储后端和缓存. 在第一次安装过程中,我遇到了一些问题 ...
- MVC中提交包含HTML代码的页面处理方法(尤其是在使用kindeditor富文本编辑器的时候)
针对文本框中有HTML代码提交时,mvc的action默认会阻止提交,主要是出于安全考虑.如果有时候需求是要将HTML代码同表单一起提交,那么这时候我们可以采取以下两种办法实现: 1.给Control ...
- Regasm
程序集注册工具(Regasm.exe) 读取程序集中的元数据,并将所需的项添加到注册表中.注册表允许COM 客户程序以透明方式创建.NET Framework类.类一经注册,任何COM 客户程序都 ...
- Codeforces543BDestory Roads心得
题目描述: In some country there are exactly n cities and m bidirectional roads connecting the cities. Ci ...
- pytesseract使用
1.安装pip install pytesseract 2.安装tesseract-ocr,下载地址:https://github.com/UB-Mannheim/tesseract/wiki,我安装 ...
- 前端测试框架Jest系列教程 -- 简介
写在前面: 随着互联网日新月异的发展,用户对于页面的美观度,流畅度以及各方面的体验有了更高的要求,我们的网页不再是简单的承载文字,图片等简单的信息传递给用户,我们需要的是更加美观的页面展示,更快的浏览 ...
- angular中复制文字到剪切板
function copyToClipboard(oElement, value) { var aux = document.createElement("input"); if ...
- nefu 115 循环节
斐波那契的整除 Problem:115 Time Limit:1000ms Memory Limit:65536K Description 已知斐波那契数列有如下递归定义,f(1)=1,f(2)=1, ...
- 深入理解php内核 编写扩展 I:介绍PHP和Zend
内容: 编写扩展I - PHP和Zend起步 原文:http://devzone.zend.com/public/view/tag/Extension Part I: Introduction to ...
- angularjs 给封装的模态框元素传值,和实现兄弟传值
本例实现封装的元素所放的位置不同,而选择不同的传值,这里举例封装了bootstrap模态框,以后也方便大家去直接使用.方法举例如下:首先主页调用css/js有: <link rel=" ...