热防止按钮单击时的默认事件 [英] Hot to prevent default event when button click
问题描述
我有按钮点击事件
private void AnswerPressAction(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
Button validButton = null;
string buttonName = button.Name;
button.Background = new SolidColorBrush(Colors.Yellow);
System.Threading.Thread.Sleep(1000);
int presedAnswer = 0;
switch (buttonName)
{
case "buttonAnswer1":
presedAnswer = 1;
break;
case "buttonAnswer2":
presedAnswer = 2;
break;
case "buttonAnswer3":
presedAnswer = 3;
break;
case "buttonAnswer4":
presedAnswer = 4;
break;
}
switch (_valid_answer)
{
case 1:
validButton = buttonAnswer1;
break;
case 2:
validButton = buttonAnswer2;
break;
case 3:
validButton = buttonAnswer3;
break;
case 4:
validButton = buttonAnswer4;
break;
}
if (presedAnswer != 0 && presedAnswer == _valid_answer)
{
button.Background = new SolidColorBrush(Colors.Green);
System.Threading.Thread.Sleep(1000);
CreateQuestion(1);
}
else
{
button.Background = new SolidColorBrush(Colors.Red);
validButton.Background = new SolidColorBrush(Colors.Green);
System.Threading.Thread.Sleep(1000);
_gameLevel = 0;
}
}
并且我将在此功能中更改按钮颜色,但是,按钮被按下并且我无法更改颜色(按钮处于活动状态/按下).
and i will change button color in this function, but, button is pressed and i can't change color (button is active/pressed).
如何像 javascript e.preventDefault()
,或者在按钮未激活时在按钮按下之前运行此事件?
how do like javascript e.preventDefault()
, or run this event before button pressed, when button is not active?
推荐答案
问题是您使用 Sleep
调用阻塞了线程.如果您想引入延迟,请查看 Task.Delay
方法.您需要了解一些 async
方法(MSDN 上有大量示例,或者您可以搜索 SO).
The issue is that you are blocking the thread with the Sleep
call. If you want to introduce a delay, look into the Task.Delay
method. You will need to learn a little bit about async
methods (plenty of examples on MSDN or you can search SO).
很可能你需要在 await
延迟时禁用你的 UI,因为延迟允许 UI 继续更新(并显示你想要的颜色变化)但它也允许用户与 UI 交互(例如,再次单击按钮,或单击不同的按钮).Enabled
属性在这里会有所帮助.
Most likely you will need to disable your UI while await
ing the delay, since the delay allows the UI to continue to update (and show the color change you desire) but it also allows the user to interact with the UI (eg, to click the button a second time, or click a different button). The Enabled
property will help here.
这篇关于热防止按钮单击时的默认事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!