Hot to prevent default event when button click

谁说胖子不能爱 提交于 2019-12-12 04:17:52

问题


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?


回答1:


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 awaiting 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.



来源:https://stackoverflow.com/questions/34579921/hot-to-prevent-default-event-when-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!