顾名思义就是装饰用的,也就是说不改变原有的控件结构,但可以为控件添加一些新的功能,或是为控件的显示外观增加些东西。 我们以MSDN中的代码为例(装饰器概述)做延伸:
xaml:
<UserControl x:Class="MyWpf.MyAdorner" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MyWpf" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition Height="100"></RowDefinition> </Grid.RowDefinitions> <Button Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="show" Width="200" Height="100" ></Button> <StackPanel Grid.Row="1" HorizontalAlignment="Center" Orientation="Horizontal"> <Button Content="增加装饰器" x:Name="add" Width="77" Height="30" HorizontalAlignment="Center" Click="Add_Click"></Button> <Button Content="移除装饰器" HorizontalAlignment="Center"
x:Name="delete" Height="30" Click="Delete_Click" Margin="2,0,0,0" Width="89"/> </StackPanel> </Grid> </UserControl>
后台代码:
namespace MyWpf { /// <summary> /// MyAdorner.xaml 的交互逻辑 /// </summary> public partial class MyAdorner : UserControl { public MyAdorner() { InitializeComponent(); } private void Add_Click(object sender, RoutedEventArgs e) { //拿到被装饰的控件装饰层 var layer = AdornerLayer.GetAdornerLayer(show); //将装饰的信息放到被装饰控件的装饰层中 layer.Add(new TestAdorner(show)); } private void Delete_Click(object sender, RoutedEventArgs e) { var layer = AdornerLayer.GetAdornerLayer(show); var arr = layer.GetAdorners(show); if (arr != null) { //不一定有多少装饰器,所以全部删除 for (int i = arr.Length - 1; i >= 0; i--) { layer.Remove(arr[i]); } } } } /// <summary> /// 自定义的装饰器类 /// </summary> public class TestAdorner : Adorner { public TestAdorner(UIElement adornedElement) : base(adornedElement) { } // A common way to implement an adorner's rendering behavior is to override the OnRender // method, which is called by the layout system as part of a rendering pass. protected override void OnRender(DrawingContext drawingContext) { Rect adornedElementRect = new Rect(this.AdornedElement.DesiredSize); // Some arbitrary drawing implements. SolidColorBrush renderBrush = new SolidColorBrush(Colors.Green); renderBrush.Opacity = 0.2; Pen renderPen = new Pen(new SolidColorBrush(Colors.Navy), 1.5); double renderRadius = 5.0; // Draw a circle at each corner. drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.TopLeft, renderRadius, renderRadius); drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.TopRight, renderRadius, renderRadius); drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.BottomLeft, renderRadius, renderRadius); drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.BottomRight, renderRadius, renderRadius); } } }
结果: