What is an Adorner in WPF?

Adorners are a special type of FrameworkElement, used to provide visual cues to a user. Among other uses, Adorners can be used to add functional handles to elements or provide state information about a control.

An Adorner is a custom FrameworkElement that is bound to a UIElement. Adorners are rendered in an AdornerLayer, which is a rendering surface that is always on top of the adorned element or a collection of adorned elements. Rendering of an adorner is independent from rendering of the UIElement that the adorner is bound to. An adorner is typically positioned relative to the element to which it is bound, using the standard 2-D coordinate origin located at the upper-left of the adorned element.

Where to use adorners?

Adorners can be used for following scenarios:

·         Adding functional handles to a UIElement that enable a user to manipulate the element in some way (resize, rotate, reposition, etc.).

·         Provide visual feedback to indicate various states, or in response to various events.

·         Overlay visual decorations on a UIElement.

·         Visually mask or override part or all of a UIElement.

 

Here is an example which shows how to implement  an Adorner

// Adorners must subclass the abstract base class Adorner.

public class SimpleCircleAdorner : Adorner

{

  // Be sure to call the base class constructor.

  public SimpleCircleAdorner(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);

  }

}

 

 

References:

1.       WPF Adorners Overview