2016-03-21 10 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

VisualChildrenCountプロパティとGetVisualChild()派生UIElementまたはFrameworkElementメソッドをオーバーライドして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 }); 
関連する問題