Windows Phone 在方法 运行 时操作元素

Windows Phone manipulate element when method running

QuestionNumber.Foreground tap 变红之前,我尝试用这段代码进行测试:

private void QuestionNumber_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        QuestionNumber.Foreground = new SolidColorBrush(Colors.Gray);
        System.Threading.Thread.Sleep(1000);
        QuestionNumber.Foreground = new SolidColorBrush(Colors.Yellow);
    }

结果:1 秒后 QuestionNumber 前景为黄色,但点击后我看不到灰色

永远不要在 UI 线程上使用 System.Threading.Thread.Sleep(...),因为它会阻塞整个应用程序(应用程序不会对任何用户输入做出反应,UI 也不会已更新,这就是为什么您看不到颜色变化的原因。

出于测试目的,您可以将 Thread.Sleep 替换为 Task.Delay:

private async void QuestionNumber_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    QuestionNumber.Foreground = new SolidColorBrush(Colors.Gray);
    await System.Threading.Tasks.Task.Delay(1000);
    QuestionNumber.Foreground = new SolidColorBrush(Colors.Yellow);
}

(请注意方法签名中的关键字 async,这是等待调用 Task.Delay 所必需的。)

确切地说,使用任务,代码将按预期执行并显示结果。

睡眠使应用成为墓碑