Reputation: 2646
I have a RenderChart
method encaspsulated in the code behind of a UserControl
which will hopefully draw some charts on a map. I have simplified the method to try to get some text rendered but without success:
private void RenderChart()
{
DrawingVisual newVisual = new DrawingVisual();
using (DrawingContext dc = newVisual.RenderOpen())
{
Rect rect = new Rect(new Point(160, 100), new System.Windows.Size(320, 80));
dc.DrawRectangle(Brushes.Maroon, (Pen)null, rect);
dc.Close();
}
if (this.visual != null)
{
this.RemoveVisualChild(this.visual);
}
this.AddVisualChild(newVisual);
this.visual = newVisual;
this.RefreshMargin();
}
Whenever I've drawn simple shapes etc before I've used for example myCanvas.Children.Add(myEllipse);
Infact If I define an Ellipse & add it to a canvas as abovewithout using the DrawingContext I get the result I expect.
Do I need to add the drawing context to a panel in my control or is there some other reason as to why is won't render in the UI?
Upvotes: 0
Views: 900
Reputation: 5421
The UserControl
class ultimately derives from a class called UIElement
, which defines a virtual OnRender
method that you can override to "draw" on the control (as Clemens suggests in a question comment). The following example will draw a blue rectangle the same size as the user control:
protected override void OnRender(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Blue, null, new Rect(0, 0, ActualWidth, ActualHeight));
}
I would suggest that overriding OnRender
is the more traditional way to approach this rather than attempting to use a DrawingVisual
. The only potential issue you might have with this technique is that your drawing will appear behind all of the other controls contained in your user control.
Upvotes: 1