当前位置:网站首页>C WPF additional attribute implementation interface defines decorator
C WPF additional attribute implementation interface defines decorator
2022-06-23 07:28:00 【CodeOfCC】
List of articles
Preface
A decorator is wpf A component that can float above a control in , We can usually use it to implement some controls, such as dragging points 、 Prompt box 、 Customize the mouse and other interface functions . The use of decorators is actually quite complicated , Almost completely re cs Write all the code in , In case of high style requirements , It's all in cs The style of some controls in is difficult . In order to change this situation , We can use additional attributes to encapsulate the decorator's logic , Provide a property that can be defined on the interface .
One 、 How to achieve ?
1、 Implement decorators
because Adorner Is an abstract class that cannot be implemented directly , So we need to define a subclass and implement it .
class NormalAdorner : Adorner
{
/// <summary>
/// Construction method
/// </summary>
/// <param name="adornedElement"> The element to which the decorator is added </param>
/// <param name="child"> Elements placed in the decorator </param>
public NormalAdorner(UIElement adornedElement, UIElement child) : base(adornedElement);
protected override Visual GetVisualChild(int index);
protected override int VisualChildrenCount;
protected override Size ArrangeOverride(Size finalSize);
}
2、 Define additional properties
adopt propa Quickly define a name as AdornerContent The additional properties of its type UIElement.
public static UIElementGetAdornerContent(DependencyObject obj)
{
return (UIElement)obj.GetValue(AdornerContent);
}
public static void SetAdornerContent(DependencyObject obj, Control value)
{
obj.SetValue(AdornerContent, value);
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AdornerContent =
DependencyProperty.RegisterAttached("AdornerContent", typeof(UIElement), typeof(AdornerHelper), new PropertyMetadata(null));
3、 Add decorative layer
In the additional attribute change event , Add decorative layer .
public void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var c = d as UIElement;
// Get decorative layer
var layer = AdornerLayer.GetAdornerLayer(c);
// Add decorators
layer.Add(new NormalAdorner(c, (UIElement)e.NewValue));
}
Two 、 Complete code
AdornerHelper.cs
using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace AC
{
internal class AdornerHelper
{
public static UIElement GetAdornerContent(DependencyObject obj)
{
return (UIElement)obj.GetValue(AdornerContent);
}
public static void SetAdornerContent(DependencyObject obj, UIElement value)
{
obj.SetValue(AdornerContent, value);
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AdornerContent =
DependencyProperty.RegisterAttached("AdornerContent", typeof(UIElement), typeof(AdornerHelper), new PropertyMetadata(null, (d, e) =>
{
var c = d as FrameworkElement;
if (c == null)
return;
var adronerContent = e.NewValue as UIElement;
if (!c.IsLoaded)
{
if (adronerContent != null)
{
RoutedEventHandler l = null;
l = (s, E) =>
{
var content = GetAdornerContent(c);
if (content != null)
{
var layer = AdornerLayer.GetAdornerLayer(c);
if (layer == null)
throw new Exception(" Failed to get control decoration layer , Control may not have a decorative layer !");
layer.Add(new NormalAdorner((UIElement)c, (UIElement)e.NewValue));
}
c.Loaded -= l;
};
c.Loaded += l;
}
}
else
{
var layer = AdornerLayer.GetAdornerLayer(d as Visual);
if (layer == null)
throw new Exception(" Failed to get control decoration layer , Control may not have a decorative layer !");
if (e.OldValue != null)
{
var adorners = layer.GetAdorners(c);
foreach (var i in adorners)
{
if (i is NormalAdorner)
{
var na = i as NormalAdorner;
if (na.Child == e.OldValue)
{
layer.Remove(i);
break;
}
}
}
}
if (adronerContent != null)
{
layer.Add(new NormalAdorner((UIElement)c, (UIElement)e.NewValue));
}
}
}));
class NormalAdorner : Adorner
{
UIElement _child;
/// <summary>
/// Construction method
/// </summary>
/// <param name="adornedElement"> The element to which the decorator is added </param>
/// <param name="child"> Elements placed in the decorator </param>
public NormalAdorner(UIElement adornedElement, UIElement child) : base(adornedElement)
{
_child = child;
AddVisualChild(child);
}
public UIElement Child {
get {
return _child; } }
protected override Visual GetVisualChild(int index)
{
return _child;
}
protected override int VisualChildrenCount
{
get
{
return 1;
}
}
protected override Size ArrangeOverride(Size finalSize)
{
_child.Arrange(new Rect(new Point(0, 0), finalSize));
return finalSize;
}
}
}
}
3、 ... and 、 Examples of use
<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp2" xmlns:ac="clr-namespace:AC" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800" >
<Grid>
<Border Background="RoyalBlue" Width="320" Height="180" CornerRadius="10">
<!-- Add decorators -->
<ac:AdornerHelper.AdornerContent>
<Grid >
<Grid.Resources>
<Style TargetType="Thumb"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Thumb"> <Border BorderBrush="Gray" BorderThickness="2" CornerRadius="8" Background="White"></Border> </ControlTemplate> </Setter.Value> </Setter> </Style>
</Grid.Resources>
<!-- Left -->
<Thumb Margin="-8,0,0,0" Width="16" Height="16" HorizontalAlignment="Left" VerticalAlignment="Center" Cursor="SizeWE"/>
<!-- On -->
<Thumb Margin="0,-8,0,0" Width="16" Height="16" HorizontalAlignment="Center" VerticalAlignment="Top" Cursor="SizeNS"/>
<!-- Right -->
<Thumb Margin="0,0,-8,0" Width="16" Height="16" HorizontalAlignment="Right" VerticalAlignment="Center" Cursor="SizeWE"/>
<!-- Next -->
<Thumb Margin="0,0,0,-8" Width="16" Height="16" HorizontalAlignment="Center" VerticalAlignment="Bottom" Cursor="SizeNS"/>
<!-- Top left -->
<Thumb Margin="-8,-8,0,0" Width="16" Height="16" HorizontalAlignment="Left" VerticalAlignment="Top" Cursor="SizeNWSE"/>
<!-- The upper right -->
<Thumb Margin="0,-8,-8,0" Width="16" Height="16" HorizontalAlignment="Right" VerticalAlignment="Top" Cursor="SizeNESW"/>
<!-- The lower right -->
<Thumb Margin="0,0,-8,-8" Width="16" Height="16" HorizontalAlignment="Right" VerticalAlignment="Bottom" Cursor="SizeNWSE"/>
<!-- The lower left -->
<Thumb Margin="-8,0,0,-8" Width="16" Height="16" HorizontalAlignment="Left" VerticalAlignment="Bottom" Cursor="SizeNESW"/>
</Grid>
</ac:AdornerHelper.AdornerContent>
</Border>
</Grid>
</Window>
Results the preview 
summary
That's what we're going to talk about today , The main purpose of defining decorators on the interface is to write complex styles , The usage has changed a lot . If you want to use it flexibly, you need to wpf Have a certain in-depth understanding . But from another point of view, define decorators and use them on the interface Grid The layout adjustment cascade achieves the same effect , It may not be much different in essence , At least the two are identical in the control tree . Generally speaking, I think this is an interesting way to use decorators .
边栏推荐
猜你喜欢

SimpleDateFormat 线程安全问题

闫氏DP分析法

Ntu-rgbd data set download and data format analysis

GINet

Pagoda forgot password

小爱音箱连接网络异常解决办法

Live broadcast review | how can the container transformation of traditional applications be fast and stable?

MySQL Niuke brush questions

Yan's DP analysis

CIRIUM(睿思誉)逐渐成为航空公司二氧化碳排放报告的标准
随机推荐
传智教育 | 多人协作开发出现代码冲突,如何合并代码?
900. RLE iterator
npm下载报错npm ERR code ERESOLVE
[2022 graduation season] from graduation to transition to the workplace
MySQL (VIII) - explain
【AI实战】XGBRegressor模型加速训练,使用GPU秒级训练XGBRegressor
SimpleDateFormat 线程安全问题
Specific help of OSI layered model to work
Focusing on the industry, enabling customers | release of solutions for the five industries of the cloud container cloud product family
MySQL (11) - sorting out MySQL interview questions
Unet代码实现
微信多人聊天及轮盘小游戏(websocket实现)
What is the experience of being a data product manager in the financial industry
[* * * array * * *]
控制台程序
闫氏DP分析法
Elaborate on the operation of idea
MySQL(二) — MySQL数据类型
Use of Lombok
Arthas-thread命令定位线程死锁