Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redraw or refresh in OnRender?

I want to draw something dynamically. Following code shows my OnRender. I'm setting DrawItem somewhere in my program where I need it. But when I'm calling DrawItem =5; what do I have to call, so that OnRender gets called?

protected override void OnRender(DrawingContext drawingContext)
{
    switch (DrawItem)
    {
        case 1:
            //Draw Item 
            break;
        case 2:
            //Draw Item 
            break;
        case 3:
            //Draw Item 
            break;
        case 4:
            //Draw Item 
            break;
        case 5:
            //Draw Item 
            break;
    }
    base.OnRender(drawingContext)
}

public int DrawItem { get; set; }
like image 350
David Avatar asked May 14 '12 14:05

David


2 Answers

If the size of your control changes, you can use InvalidateVisual(), however keep in mind this causes a fairly expensive re-layout of your UI. If the size of your control is staying the same, you shouldn't call InvalidateVisual().

A more efficient way to update your UI is to create a DrawingGroup "backing store" and add it to the DrawingContext during OnRender(). You can then update it whenever you like, using DrawingGroup.Open(), and WPF will update your UI.

If this sounds confusing, remember that WPF is a retained drawing system. That means OnRender() might better be called AccumulateDrawingObjects(). It's actually accumulating a tree of live drawing objects, some of which (like DrawingGroup, RenderTargetBitmap, and WriteableBitmap) can be updated later.

This is what it looks like:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {      
    base.OnRender(drawingContext);            

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {            
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();            
}
like image 78
David Jeske Avatar answered Oct 29 '22 04:10

David Jeske


Your question is not clear but from what I can understand you seem to be asking for a method to refresh the visuals after updating your drawing variables. You could use the following after updating your drawing variables:

this.InvalidateVisual();

and with the property:

private int drawItem;
pulic int DrawItem
{
 get {return drawItem;}
 set 
 {
    drawItem=value;
    this.InvalidateVisual();
 }
}
like image 20
Indy9000 Avatar answered Oct 29 '22 02:10

Indy9000