DrawingContext adorner - possible to draw stackpanel?
Asked Answered
F

1

4

Using the DrawingContext class I've been able to use the DrawRectangle() method to successfully add an adorner to my adornedElement.

Is it possible to construct a stackpanel, with a textbox and image inside - and assign this as the adorner?

I'm using visual studio 2010 by the way - not microsoft expression.

Thanks a lot,

Dan

Fleischer answered 20/12, 2011 at 13:58 Comment(0)
G
14

No, this is not possible out of the box as the DrawingContext is only meant to draw Visuals and no FrameworkElements. What you can do is create your own Adorner which is able to draw FrameworkElements:

  public class FrameworkElementAdorner : Adorner
  {
    private FrameworkElement _child;

    public FrameworkElementAdorner(UIElement adornedElement)
      : base(adornedElement)
    {
    }

    protected override int VisualChildrenCount
    {
      get { return 1; }
    }

    public FrameworkElement Child
    {
      get { return _child; }
      set
      {
        if (_child != null)
        {
          RemoveVisualChild(_child);
        }
        _child = value;
        if (_child != null)
        {
          AddVisualChild(_child);
        }
      }
    }

    protected override Visual GetVisualChild(int index)
    {
      if (index != 0) throw new ArgumentOutOfRangeException();
      return _child;
    }

    protected override Size MeasureOverride(Size constraint)
    {
      _child.Measure(constraint);
      return _child.DesiredSize;
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
      _child.Arrange(new Rect(new Point(0, 0), finalSize));
      return new Size(_child.ActualWidth, _child.ActualHeight);
    }
  }

Usage:

  var fweAdorner = new FrameworkElementAdorner(adornedElement);

  //Create your own Content, here: a StackPanel with some stuff inside
  var stackPanel = new StackPanel();
  stackPanel.Children.Add(new TextBox() { Text="TEST"});
  stackPanel.Children.Add(new Image());

  fweAdorner.Child = stackPanel;

  var adornerLayer = AdornerLayer.GetAdornerLayer(adornedElement);
  adornerLayer.Add(fweAdorner);

You could also incorporate the creation of the StackPanel directly in the Adorner if you use this combination of a StackPanel multiple times. That depends on your scenario.

Godbeare answered 20/12, 2011 at 14:25 Comment(1)
Sven, can't thank you enough mate!! Straight copied and pasted into my solution and it works a charm!!! THANKS!Fleischer

© 2022 - 2024 — McMap. All rights reserved.