专栏首页dino.c的专栏[UWP 自定义控件]了解模板化控件(6):使用附加属性

[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);
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • [UWP]附加属性1:概述

    附加属性依赖属性的一种特殊形式,常见的Grid.Row,Canvas.Left都是附加属性。

    dino.c
  • [UWP]用Win2D和CompositionAPI实现文字的发光效果,并制作动画

    献祭了周末的晚上,成功召唤出了上面的番茄钟。正当我在感慨“不愧是Shadow大人,这难道就是传说中的五彩斑斓的黑?”

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

    是不是觉得它们中出了一个叛徒?这个示例中除了ListBox控件其它都自带Header,但是ListBox没有Header属性,只好用一个TextBlock模仿它...

    dino.c
  • Hdu 1709 The Balance

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1709

    若羽
  • [编程题] 集合代码

    小易最近在数学课上学习到了集合的概念,集合有三个特征:1.确定性 2.互异性 3.无序性.小易的老师给了小易这样一个集合:S = { p/q | w ≤ p ≤...

    desperate633
  • C#生成二维码,裁切边框

    使用google zxing生成的二维码带有白色边框,显示在报告(使用Crystal Report 水晶报表)上时,由于空间有限造成二维码过小难以扫描识别。 通...

    用户1637609
  • IDEA自动导包

    说故事的五公子
  • 如何通过编程改变生涯

    文章来自:博客 http://www.nowamagic.net/librarys/news/detail/2237 如果你想知道如何学习编程和转行,那么你不是...

    企鹅号小编
  • Web-第三十一天 WebService学习【悟空教程】

    简单的网络应用使用单一语言写成,它的唯一外部程序就是它所依赖的数据库。大家想想是不是这样呢?

    Java帮帮
  • 矩阵连乘

    矩阵AB可乘的条件是矩阵A的列数等于矩阵B的行数 计算时,加括号方式,对计算量的影响很大 穷举搜索法:来搜索可能的计算次序,并计算出每一种计算次序相应需要的数乘...

    用户1154259

扫码关注云+社区

领取腾讯云代金券