[WPF系列]-Adorner

2023-07-29,,

 

简介

通常我们想对现有的控件,做些修饰时我们就会想到一个装饰模式。WPF中也提供了这样的实现思路:通过将Adorner添加到AdornerLayer中来实现装饰现有控件的效果。如图示:

 

本来TextBox四角没有圆点,但是通过装饰器可以为它加上。所以可以看成在TextBox上加了层。

 

这样就“无痛”的给控件进行了装饰(如果不想要,还可以随时拆掉,哈哈)。当然应用不单单这样加几个点而已,修饰嘛比如拖动控件的修饰。

 

编程方式给指定UIElement添加装饰器

此示例演示如何以编程方式将装饰器绑定到指定的 UIElement。

若要将装饰器绑定到特定的 UIElement,请按照以下步骤操作:

 

    调用 static 方法 GetAdornerLayer,为要装饰的 UIElement 获得 AdornerLayer 对象。 GetAdornerLayer 从指定的 UIElement 开始沿着可视化树向上行进,返回它所发现的第一个装饰器层。 (如果未发现装饰器层,则该方法返回 Null。)

    调用 Add 方法将装饰器绑定到目标 UIElement

myAdornerLayer = AdornerLayer.GetAdornerLayer(myTextBox);
myAdornerLayer.Add(new SimpleCircleAdorner(myTextBox));

 

使用XAML方式给指定UIElement添加装饰器

 

<AdornerDecorator>
<TextBox Text="可以得到AdornerLayer"/>
</AdornerDecorator>

 

 

 

 

参考

AdornerLayer.GetAdornerLayer 方法

AdornerLayer 类

WPF自定义控件 —— 装饰器

[WPF系列]-Adorner的相关教程结束。

《[WPF系列]-Adorner.doc》

下载本文的Word格式文档,以方便收藏与打印。