【问题标题】:Hot to prevent default event when button click热以防止按钮单击时的默认事件
【发布时间】:2016-01-04 13:02:56
【问题描述】:

我有按钮点击事件

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;
        }
    }

我将在此函数中更改按钮颜色,但是,按钮被按下并且我无法更改颜色(按钮处于活动状态/按下状态)。

当按钮不活动时,如何喜欢 javascript e.preventDefault(),或者在按下按钮之前运行此事件?

【问题讨论】:

  • 或者请告诉我在这个事件之后如何运行我的方法
  • 你为什么打Thread.Sleep(1000);电话?
  • 我想改变颜色,停留 1 秒,然后再改变颜色。这点赞游戏Who Wants to Be a Millionaire?
  • 您正在休眠 UI 线程,因此它无法更新颜色。您需要让 UI 线程在颜色发生变化之前完成该方法。
  • 尝试使用此代码设置presedAnswer:int presedAnswer = int.Parse(buttonName.Substring("buttonAnswer".Length));

标签: c# windows-phone-8 windows-phone


【解决方案1】:

问题是您正在使用Sleep 调用阻塞线程。如果您想引入延迟,请查看Task.Delay method。您将需要了解一点async 方法(MSDN 上有大量示例,或者您可以搜索 SO)。

您很可能需要在await延迟时禁用您的 UI,因为延迟允许 UI 继续更新(并显示您想要的颜色更改),但它也允许用户与 UI 交互(例如,再次单击按钮,或单击不同的按钮)。 Enabled 属性将在这里提供帮助。

【讨论】:

  • 谢谢,我尝试使用asyc,我认为还有另一种解决方案
  • @ned - 在这里使用async 是一个非常简洁的解决方案。您还考虑使用什么其他解决方案?
  • @Enigmativity,我是初学者,我首先需要学习如何运行异步方法)))
  • 如果您想要其他解决方案,请查看DispatcherTimer(但更复杂)。
  • @ned - 就像在 async 方法中调用 await Task.Delay(TimeSpan.FromSeconds(1.0)); 一样简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 2011-02-22
  • 2017-11-09
  • 1970-01-01
相关资源
最近更新 更多