我有一个 WPF Canvas ,我想在其中每 x 毫秒显示不同颜色的 Rectangles(存储在多维数组中)。
Random rnd = new Random();
foreach (var i in Enumerable.Repeat(1, 100))
{
_rectGrid[rnd.Next(0, 30), rnd.Next(0, 30)].Fill = new SolidColorBrush(Colors.Blue);
Thread.Sleep( 100 );
// refresh somehow here?
}
这有效,但我没有看到它实时更新,因为它在 MainWindow 构造函数中。
很明显,矩形必须在 GUI 线程中创建,但如果我创建一个 Timer 来更改它在不同线程中的颜色。
我能否创建一个多维值数组并将这些值绑定(bind)到矩形数组中的颜色,以便我可以从另一个线程访问它们?如果这样做,我该如何告诉 GUI 线程重绘?
也许让用户先点击一个按钮会更简单,这样构造函数中就不会发生这种情况?
编辑:
DispatcherTimer 工作得很好。我不明白为什么 MS 有一个单独的类(class)。
Here是我使用它的来源。
请您参考如下方法:
您可以使用 DispatcherTimer像这样:
public MainWindow()
{
InitializeComponent();
DispatcherTimer t = new DispatcherTimer();
t.Tick += t_Tick;
t.Interval = new TimeSpan(0, 0, 0, 0, 300);
t.Start();
}
Random r = new Random();
void t_Tick(object sender, EventArgs e)
{
byte[] rnd = new byte[4];
r.NextBytes(rnd);
this.Background = new SolidColorBrush(Color.FromArgb(rnd[0], rnd[1], rnd[2], rnd[3]));
}
