5

我有一个绘图视觉,我有绘图,如何将它添加到我的画布和显示?

 DrawingVisual drawingVisual = new DrawingVisual();

 // Retrieve the DrawingContext in order to create new drawing content.
 DrawingContext drawingContext = drawingVisual.RenderOpen();

 // Create a rectangle and draw it in the DrawingContext.
 Rect rect = new Rect(new System.Windows.Point(0, 0), new System.Windows.Size(100, 100));
 drawingContext.DrawRectangle(System.Windows.Media.Brushes.Aqua, (System.Windows.Media.Pen)null, rect);

 // Persist the drawing content.
 drawingContext.Close();

如何将此添加到画布?假设我有一个 Canvas 作为

  Canvas canvas = null;
  canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.

如何将我的绘图视觉添加到画布?

TIA。

4

1 回答 1

14

您必须实现一个宿主元素类,它必须覆盖派生的 UIElement 或 FrameworkElement 的VisualChildrenCount属性和GetVisualChild()方法才能返回您的 DrawingVisual。

最基本的实现可能如下所示:

public class VisualHost : UIElement
{
    public Visual Visual { get; set; }

    protected override int VisualChildrenCount
    {
        get { return Visual != null ? 1 : 0; }
    }

    protected override Visual GetVisualChild(int index)
    {
        return Visual;
    }
}

现在你可以像这样向你的画布添加一个视觉对象:

canvas.Children.Add(new VisualHost { Visual = drawingVisual });
于 2016-03-21T09:11:17.757 回答