问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/8576594/drawingcontext-adorner-possible-to-draw-stackpanel