WPF forcing redraw of canvas

后端 未结 4 1434
孤街浪徒
孤街浪徒 2020-12-31 10:59

Okay, in windows forms you can use .refresh() to cause a redraw event on an element. Is there a similar solution in WPF?

An explanation of what I\'m doi

相关标签:
4条回答
  • 2020-12-31 11:15

    this work for me...

    element.UpdateLayout();
    
    0 讨论(0)
  • 2020-12-31 11:18

    This is what you are looking for...

    element.InvalidateVisual();
    
    0 讨论(0)
  • 2020-12-31 11:28

    You probably want to use the Dispatcher object. I suggest you take a look a this Shawn Wildermuth's article: Build More Responsive Apps With The Dispatcher (MSDN magazine October 2007).

    0 讨论(0)
  • 2020-12-31 11:32

    Without a good Minimal, Complete, and Verifiable code example to show clearly what you're doing, it's impossible to know for sure what the best answer here is. However, from your description it sounds as though the maze-generating algorithm is executing in the UI thread, blocking the UI from updating itself.

    Just as in the case with Winforms, where people are tempting to call methods like Refresh() or Application.DoEvents(), the real problem here is that you're blocking the UI thread. The right way to fix that is, don't do that.

    There are lots of alternatives and without a more detailed question there's no way to know what would be the best approach in your case. However, the two most commonly used and most likely to be appropriate techniques are to use BackgroundWorker, or Task.Run() in combination with the Progress<T> class. In either case, your algorithm runs in a different thread, passing updates to the UI thread periodically (e.g. every rectangle, every ten rectangles, whatever). The UI thread receives an update, adds the data to the visuals, and then goes back to waiting for the next update.

    BackgroundWorker and Progress<T> both provide built-in mechanisms for automatically marshalling data back to the UI thread. The only caveat is that whichever of those classes you're using, the instance of that class needs to be created on the UI thread. Since they need to be set up before you start executing the asynchronous work, this is typically not a problem; it comes for free.

    If you do it this way, you won't need any hacks such as the three different ones that have been suggested here so far (two of which don't seem likely to be applicable in the "I've blocked my UI thread, now what?" scenario anyway).

    0 讨论(0)
提交回复
热议问题