I have button click event
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).
how do like javascript e.preventDefault()
, or run this event before button pressed, when button is not active?
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).
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.