簡體   English   中英

在 Xamarin 中,如何在 1 秒內更改按鈕的背景顏色並再次將其恢復為原始顏色?

[英]In Xamarin, how can I change the background color of a button for just 1 second and return it again to its original 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(1000).Wait();                     // waiting 1 second            
btnCancel.BackgroundColor = auxColor;        // restoring the original color

但我得到的是以下序列:

1-保存原始顏色
2-等待 1 秒
3 將顏色更改為紅色
4 立即恢復顏色

有誰知道如何解決這個問題?

您可以通過以下方式使用Device.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
});

請參閱Device.StartTimer文檔。

看起來您正在調用由主線程執行的方法中的語句,該主線程也負責渲染。 這意味着你的陳述

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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM