2016-03-21 89 views
2

我有繪畫視覺,我有繪畫,如何將其添加到我的畫布和顯示?在畫布上顯示DrawingVisual

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 = null; 
    canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected. 

如何將我的drawingVisual添加到畫布?

TIA。

回答

3

您必須實現一個宿主元素類,該宿主元素類必須重寫派生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; 
    } 
} 

現在,您將添加一個Visual到你的Canvas這樣的:

canvas.Children.Add(new VisualHost { Visual = drawingVisual });