[英]WP7 UI updating issue
我正在動態創建5x5網格,並嘗試在這些單元格上創建動畫。 當我從程序創建開/關效果時。 我可以看到所有單元都同時打開或關閉,而不是單獨打開。
這是代碼。 我在這里做錯了什么?
private CellControl[,] Lights;
private void CreateGrid()
{
for (int i = 0; i < 5; i++)
{
ColumnDefinition cd = new ColumnDefinition() { Width = new GridLength(20, GridUnitType.Star) };
RowDefinition rd = new RowDefinition() { Height = new GridLength(20, GridUnitType.Star) };
this.GridGame.ColumnDefinitions.Add(cd);
this.GridGame.RowDefinitions.Add(rd);
}
for (int i = 0; i < GridGame.RowDefinitions.Count; ++i)
{
for (int k = 0; k < GridGame.ColumnDefinitions.Count; ++k)
{
var btn = new CellControl();
btn.TabIndex = k + (i * GridSize) + 1;
btn.State = ButtonState.On;
btn.Clicked +=new EventHandler<MouseButtonEventArgs>(btn_Clicked);
Lights[k, i] = btn;
GridGame.Children.Add(btn);
Grid.SetRow(btn, i);
Grid.SetColumn(btn, k);
}
}
}
// Animation goes here
private void AnimateGrid()
{
//Clear the grid
Dispatcher.BeginInvoke( (Action)(()=>
{
for (int y = 0; y < GridSize; y++)
for (int x = 0; x < GridSize; x++)
{
this.Lights[x, y].ToggleOff();
}
}));
int[][] lightSequence = new int[][]
{
new int[] { 1, 1 }, new int[] { 1, 2 }, new int[] { 1, 3 }, new int[] { 1, 4 }, new int[] { 1, 5 },
new int[] { 2, 5 }, new int[] { 3, 5 }, new int[] { 4, 5 }, new int[] { 5, 5 },
new int[] { 5, 4 }, new int[] { 5, 3 }, new int[] { 5, 2 }, new int[] { 5, 1 },
new int[] { 4, 1 }, new int[] { 3, 1 }, new int[] { 2, 1 },
new int[] { 2, 2 }, new int[] { 2, 3 }, new int[] { 2, 4 },
new int[] { 3, 4 }, new int[] { 4, 4 },
new int[] { 4, 3 }, new int[] { 4, 2 },
new int[] { 3, 2 }, new int[] { 2, 2 },
new int[] { 2, 3 }, new int[] { 3, 3 }
};
foreach (int[] item in lightSequence )
{
int x = item[0];
int y = item[1];
x -= 1;
y -= 1;
this.Lights[x, y].ToggleOn();
Thread.Sleep(100);
}
}
問題在於使用Thread.Sleep(100)實際上是在阻止UI線程,因此它不會立即更新。 執行完所有Thread.Sleep(100)后,將更新UI並渲染單元格(全部同時顯示)。
您必須在其他線程(例如,使用BackgroundWorker)中運行循環,然后在每次要更新UI時調用Dispatcher。
像這樣:
var bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
foreach (int[] item in lightSequence)
{
int x = item[0];
int y = item[1];
x -= 1;
y -= 1;
Dispatcher.BeginInvoke((Action<int, int>)((a, b) => this.Lights[a, b].ToggleOn()), x, y);
Thread.Sleep(100);
}
};
bw.RunWorkerAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.