C# 在Xamarin中,如何更改按钮的背景颜色仅1秒,然后将其再次恢复为原始颜色?

C# 在Xamarin中,如何更改按钮的背景颜色仅1秒,然后将其再次恢复为原始颜色?,c#,xamarin,background-color,C#,Xamarin,Background Color,我正在Xamarin中开发一个小应用程序,我想在用户按下按钮时只改变按钮的背景色1秒。我尝试使用的代码如下所示: var auxColor = btnCancel.BackgroundColor; // saving the original color (btnCancel is the button name) btnCancel.BackgroundColor = Color.Red; // changing the color to red Task.Delay(100

我正在Xamarin中开发一个小应用程序,我想在用户按下按钮时只改变按钮的背景色1秒。我尝试使用的代码如下所示:

var auxColor = btnCancel.BackgroundColor;    // saving the original color (btnCancel is the button name)
btnCancel.BackgroundColor = Color.Red;       // changing the color to red
Task.Delay(1000).Wait();                     // waiting 1 second            
btnCancel.BackgroundColor = auxColor;        // restoring the original color
但我得到的是以下顺序:

1-保存原始颜色
2-等待1秒
3将颜色更改为红色
4立即恢复颜色


有人知道如何解决这个问题吗?

看起来您正在主线程执行的方法中调用steatements,该方法也负责渲染。这意味着你的陈述

Task.Delay(1000).Wait();                     // waiting 1 second   
阻止渲染,因此您的更改将不可见

有不同的方法可以解决您的问题,最简单的方法是使用异步方法,以允许UI线程在后台继续:

private async void blink()
{
    var auxColor = btnCancel.BackgroundColor;    // saving the original color (btnCancel is the button name)
    btnCancel.BackgroundColor = Color.Red;       // changing the color to red
    await Task.Delay(1000)                       // waiting 1 second            
    btnCancel.BackgroundColor = auxColor;        // restoring the original color
}
另一种可能的解决方案是在延迟完成后再次使用原始(UI)线程上下文设置原始颜色:

var auxColor = btnCancel.BackgroundColor;        // saving the original color (btnCancel is the button name)
btnCancel.BackgroundColor = Color.Red;           // changing the color to red
Task.Delay(1000).ContinueWith((T) =>             // waiting 1 second  
    {
        btnCancel.BackgroundColor = auxColor;    // restoring the original color
    }, TaskScheduler.FromCurrentSynchronizationContext());

您可以按以下方式使用
设备.StartTimer

在按钮单击事件中:

private void OnButtonClicked(object sender, EventArgs e)
{                    
    var auxColor = btnCancel.BackgroundColor;    // saving the original color 
    btnCancel.BackgroundColor = Color.Red; 

    Device.StartTimer(TimeSpan.FromSeconds(1), () =>
    {
        btnCancel.BackgroundColor = auxColor;             
        return false;
    });
}
要与UI元素交互,可以使用
BeginInvokeOnMainThread
如下:

Device.StartTimer (new TimeSpan (0, 0, 1), () =>
{
    // do something every 1 second
    Device.BeginInvokeOnMainThread (() => 
    {
      // interact with UI elements
    });
    return true; // runs again, or false to stop
});

见文件。

非常感谢你,菲利克斯。我会试试你说的。太好了!!你的方法也很有效。非常感谢,非常感谢。我也会遵循你的方法。太棒了!!两种方法都很好!非常感谢你。