wpf 如何刷新画布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15603614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh canvas
提问by sventevit
I am trying to create a visual representation of any sorting algorithm where the data is represented in an int[] array. An example of bubble sort on wikipedia:
我正在尝试创建任何排序算法的可视化表示,其中数据以 int[] 数组表示。维基百科冒泡排序的一个例子:


My sorting algorithms all raise an event ItemsSwapped when two items in the int[] array are swapped. I am trying to display the data after every event on canvas, this is my code:
当 int[] 数组中的两个项目交换时,我的排序算法都会引发一个事件 ItemsSwapped。我试图在画布上的每个事件之后显示数据,这是我的代码:
// Handler for ItemsSwapped event.
private void Render(object sender, ItemsSwapEventArgs e)
{
canvas.Children.Clear();
int numberOfElements = e.Data.Length;
for (int x = 0; x < numberOfElements; x++)
{
RenderValue(x, e.Data[x]);
}
// Here I should somehow refresh canvas.
}
private void RenderValue(int x, int y)
{
var value = new Ellipse
{
Width = 5,
Height = 5,
Stroke = Brushes.Black,
StrokeThickness = 2,
};
Canvas.SetTop(value, x);
Canvas.SetLeft(value, y);
canvas.Children.Add(value);
}
The problem is, that the canvas doesn't refresh itself, it just displays the final solution after some time. How can I refresh it after every raised event?
问题是,画布不会自行刷新,它只是在一段时间后显示最终解决方案。如何在每次引发的事件后刷新它?
Edit - I tried with UpdateLayout, InvalidateMeasure and Dispatcher object, but neither worked.
编辑 - 我尝试使用 UpdateLayout、InvalidateMeasure 和 Dispatcher 对象,但都没有奏效。
采纳答案by Vladimir
Maybe you start your sort algorithm on the UI thread, so it won't update until finished. Try sorting in another thread and update the Canvas children using the Dispatcher, by calling Invokeor BeginInvoke.
也许您在 UI 线程上启动排序算法,因此它在完成之前不会更新。尝试在另一个线程中排序并使用Dispatcher通过调用Invoke或BeginInvoke更新 Canvas 子项。
If your ItemsSwappedhandler is called from a separate thread, it may look like this:
如果您的ItemsSwapped处理程序是从单独的线程调用的,则它可能如下所示:
private void Render(object sender, ItemsSwapEventArgs e)
{
Dispatcher.Invoke((Action)(() =>
{
canvas.Children.Clear();
int numberOfElements = e.Data.Length;
for (int x = 0; x < numberOfElements; x++)
{
RenderValue(x, e.Data[x]);
}
}));
}
回答by Dima
Are you using threads? You must do your work in a separate thread from the main UI. Here is a link to get you started: How to update the GUI from another thread in C#?
你在使用线程吗?您必须在与主 UI 不同的线程中完成工作。这是一个可以帮助您入门的链接:如何从 C# 中的另一个线程更新 GUI?

