I am trying to achieve an unusual use of an Adorner. When you mouse-over a RichTextBox, an Adorner (see diagram below) will appear above it, allowing you to add a list of st
Huzah! With the help of Ghenadie Tanasiev, I've got an answer.
Unlike most controls in WPF, adorners don't have any out-of-the-box way of assigning child elements (such as the controls I wanted to add). Without adding anything to adorners, you can only override their OnRender method and draw stuff within the DrawingContext that gets passed into it. To be honest, this fits probably 99% of use cases for adorners (stuff like creating drag handles around an object), but I needed to add some proper controls to my Adorner.
The trick to doing this is to create a VisualCollection and set your adorner as its owner by passing it into the constructor for the collection.
This is all described pretty comprehensively in this blog article. Unfortunately, my repeated Google searches weren't turning this article up until I knew to search for VisualCollection, thanks to Ghenadie's guidance.
This isn't mentioned in the article, but note that it is possible to combine the VisualCollection technique along with drawing in the OnRender method of the adorner. I'm using OnRender to achieve the side and top borders described in my diagram above and using VisualCollection to place and create the controls.
Edit: here is the source code from the mentioned blog post since it is no longer available:
public class AdornerContentPresenter : Adorner
{
private VisualCollection _Visuals;
private ContentPresenter _ContentPresenter;
public AdornerContentPresenter(UIElement adornedElement)
: base(adornedElement)
{
_Visuals = new VisualCollection(this);
_ContentPresenter = new ContentPresenter();
_Visuals.Add(_ContentPresenter);
}
public AdornerContentPresenter(UIElement adornedElement, Visual content)
: this(adornedElement)
{ Content = content; }
protected override Size MeasureOverride(Size constraint)
{
_ContentPresenter.Measure(constraint);
return _ContentPresenter.DesiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
_ContentPresenter.Arrange(new Rect(0, 0,
finalSize.Width, finalSize.Height));
return _ContentPresenter.RenderSize;
}
protected override Visual GetVisualChild(int index)
{ return _Visuals[index]; }
protected override int VisualChildrenCount
{ get { return _Visuals.Count; } }
public object Content
{
get { return _ContentPresenter.Content; }
set { _ContentPresenter.Content = value; }
}
}