[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 ...
随机推荐
- codefoces384A-Mafia心得
题目描述:One day n friends gathered together to play "Mafia". During each round of the game so ...
- C#获得时间段
DateTime today = dt.Date;//今天 00:00:00 DateTime tomorrow = dt.Date.AddDays(1);//明天 00:00:00 DateTime ...
- c++ const全局对象是如何处理的
我主要是记录一个发现,目前我不能解释,先作个记录. const 只是一个 语义约束,由编译器强制实施的.使被约束的对象不能被直接访问修改. 我用 『直接』这词,因为在代码段中 ,用一个const 指针 ...
- JS--我发现,原来你是这样的JS:面向对象编程OOP[2]--(创建你的那个对象吧)
一.介绍 我们继续面向对象吧,这次是面向对象编程的第二篇,主要是讲创建对象的模式,希望大家能从博客中学到东西. 时间过得很快,还是不断的学习吧,为了自己的目标. 二.创建对象 1.前面的创建对象方式 ...
- org.springframework.web.filter.DelegatingFilterProxy的作用
一.类结构 DelegatingFilterProxy类继承GenericFilterBean,间接实现了Filter,故而该类属于一个过滤器.那么就会有实现Filter中init.doFilter. ...
- MVC中提交包含HTML代码的页面处理方法(尤其是在使用kindeditor富文本编辑器的时候)
针对文本框中有HTML代码提交时,mvc的action默认会阻止提交,主要是出于安全考虑.如果有时候需求是要将HTML代码同表单一起提交,那么这时候我们可以采取以下两种办法实现: 1.给Control ...
- tsung压力测试——tcp测试tsung.xml配置模版说明
<?xml version="1.0"?> <!DOCTYPE tsung SYSTEM "/usr/local/share/tsung/tsung-1 ...
- TensorFlow简易学习[3]:实现神经网络
TensorFlow本身是分布式机器学习框架,所以是基于深度学习的,前一篇TensorFlow简易学习[2]:实现线性回归对只一般算法的举例只是为说明TensorFlow的广泛性.本文将通过示例Ten ...
- 【Java】单词倒序输出
如何将一段单词倒序输出?把"Hello Java Hello China"变成"China Hello Java Hello"? 看起来好像很简单,只需要把字符 ...
- MS08_067漏洞学习研究
p197 MS08-067漏洞渗透攻击 按照书上的设置做,exploit得到错误信息: Exploit failed [unreachable]: Rex::ConnectionRefused The ...