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:
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:
// 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.
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 Invoke or BeginInvoke.
If your ItemsSwapped
handler is called from a separate thread, it may look like this:
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]);
}
}));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With