[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>

[UWP 自定义控件]了解模板化控件(6):使用附加属性

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);
}
}
上一篇:SAP MM PR中的Fixed ID字段与MD04里PR单据号后的星号


下一篇:FormsAuthentication.HashPasswordForStoringInConfigFile 方法 之研究