gpt4 book ai didi

c# - 从其他线程更改按钮颜色

转载 作者:行者123 更新时间:2023-11-30 22:24:23 25 4
gpt4 key购买 nike

在我的 C# 程序中,我在主 (UI) 线程中创建了一堆按钮。然后我启动一个运行 Timeline() 方法的计时器。现在,我希望按钮的外观在 Timeline() 方法运行时发生变化。但是我不允许访问这些对象,因为它们归主线程所有。我该如何解决这个问题?

错误:调用线程无法访问此对象,因为另一个线程拥有它。

我找到了 Dispatcher disp = Dispatcher.CurrentDispatcher;,它有一个 Invoke() 方法,但我不确定这是否是正确的方法,我不能'让它开始工作。

这是我的部分代码:

    private static SurfaceButton[,] buttons = new SurfaceButton[dimensionBeats, dimensionsNotes];

public SurfaceWindow1()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
}


LoadAudioContent();
// Add handlers for Application activation events
AddActivationHandlers();


InitializeButtons();

try
{
t = new Timer(Timeline, null, 1, dimensionBeats*500);
}
catch (Exception e)
{

}
}

private void InitializeButtons()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 6; j++)
{
SurfaceButton btn = new SurfaceButton();
//btn.Content = files[j].Substring(0,1);
btn.Name = "a" +i + j;
btn.Width = 120;
btn.Height = 120;
btn.ContactEnter+=StartSound;
btn.ContactLeave+=StopSound;
btn.Opacity = 0.01;
btn.ClickMode = ClickMode.Release;

buttons[i,j] = btn;

// add the newly generated button to the correct column (left to right one panel per column)
switch (i)
{
case 0:
rowPanel0.Children.Add(btn);
break;
case 1:
rowPanel1.Children.Add(btn);
break;
case 2:
rowPanel2.Children.Add(btn);
break;
case 3:
rowPanel3.Children.Add(btn);
break;
case 4:
rowPanel4.Children.Add(btn);
break;
case 5:
rowPanel5.Children.Add(btn);
break;
case 6:
rowPanel6.Children.Add(btn);
break;
case 7:
rowPanel7.Children.Add(btn);
break;
}
}
}
}


private void Timeline(Object state)
{

for (int i = 0; i < pressed.GetLength(0); i++)
{
sendRequest(url, postMethod, tabelId, buttsToString(butts));

for (int j = 0; j < pressed.GetLength(1); j++)
{
if (pressed[i,j])
{
buttons[i, j].Background = Brushes.Red;
}
}
Thread.Sleep(500);
for (int j = 0; j < pressed.GetLength(1); j++)
{
buttons[i, j].Background = Brushes.White;
}
}

最佳答案

您需要使用 Invoke/BeginInvoke 将更新转发到 GUI 线程:

int i1 = i; // local copies to avoid closure bugs
int j1 = j;
buttons[i1, j1].Dispatcher.BeginInvoke(
((Action)(() => buttons[i1, j1].Background = Brushes.Red)));

关于c# - 从其他线程更改按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12794402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com