我在运行一些代码行的按钮上有一个事件处理程序。所有代码所做的都是在列表上运行气泡排序,但也对画布上的某些矩形进行了一些更改。我的问题是,这些更改仅在退出事件处理程序后才会显示。但是,之前曾提出过类似的问题,即仅进行一次更改而不是多项优惠UI update in WPF elements event handlers。 这与我要实现的目标类似。
如果您对代码到底是什么感兴趣:
private void Run_btt_Click(object sender, RoutedEventArgs e)
{
Key hold = new Key();
var converter = new System.Windows.Media.BrushConverter();
double hold2, hold3;
//for inside a for loop(bubble sort)
for (int i = 0; i < Sequence.Count; i++)
{
for (int c = 0; c < Sequence.Count-i-1; c++)
{
//changes the colour of the 2 that are being compared
Sequence[c].shape.Fill =(Brush)converter.ConvertFromString("#FFFF00");
Sequence[c+1].shape.Fill = (Brush)converter.ConvertFromString("#FFFF00");
//pause for a bit so that you can see what the algorithm is doing
Thread.Sleep(delay);
if (Sequence[c].Value > Sequence[c + 1].Value)
{
// swap the 2 rectangles
hold2 = Canvas.GetLeft(Sequence[c].shape);
hold3 = Canvas.GetLeft(Sequence[c + 1].shape);
hold = Sequence[c];
Sequence[c] = Sequence[c + 1];
Sequence[c + 1] = hold;
Canvas.SetLeft(Sequence[c].shape, hold2);
Canvas.SetLeft(Sequence[c + 1].shape, hold3);
}
//set colour back to normal
Sequence[c].shape.Fill = (Brush)converter.ConvertFromString(Sequence[c].Colour);
Sequence[c + 1].shape.Fill = (Brush)converter.ConvertFromString(Sequence[c + 1].Colour);
}
}
}
很抱歉,这个问题太模糊或细节不够,但是我对这个话题了解不多,所以我才刚开始。感谢您的解决方案!
答案 0 :(得分:1)
只需将@Clemens评论作为答案。
如果您给方法async
如下:
public void async methodname()
,然后在需要更新UI时添加:
await Task.Delay(1);
这将像代码中的断点一样,用您所做的更改来更新UI。 1表示延迟将以毫秒为单位。