簡體   English   中英

如何在C#中等待時切換輸入字段的背景色(白色/紅色)?

[英]How can I in c# switch input field background color (white/red) on wait?

如何在C#中等待時切換輸入字段的背景色(白色/紅色)?

我是C#的初學者,問題很可能很簡單...歡迎任何建議。 謝謝!

我不明白你到底想要什么。 你可以做這樣的事情

您可以使用Task.Delay()等待

switch (id)
    {
        case 1:
            await Task.Delay(2000);
            this.BackColor = System.Drawing.Color.Red;
            break;
        case 2:
            await Task.Delay(2000);
            this.BackColor = System.Drawing.Color.White;
            break;
    }

對於“窗口窗體” ,如果要每兩秒鍾更改一次顏色,則可以使用計時器控件。 將此代碼放在您的等待代碼中

var timer = new Timer() { Interval = 2000, Enabled = true, };
        timer.Tick += (s, e) =>
            this.BackColor =
                    this.BackColor == Color.Red ? Color.White: Color.Red;

在WPF(無MVVM)中,使用TextBox作為輸入字段。 在您的.xaml文件中創建它。

<Window x:Class="TestWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox x:Name="MyTextBox" Background="Red" Margin="188,134,200.4,161.4"/>
    </Grid>
</Window>

在您的后台代碼中,也要編寫此代碼。

using System.Threading;
using System.Windows;
using System.Windows.Media;

namespace TestWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            int duration = 10; //Change this number to change the total flash duration
            double interval = 0.5; //Change this number to increase/decrease the interval between color changes.

            Thread t = new Thread(() => FlashColor(duration, interval));
            t.Start();
        }

        private void FlashColor(int duration, double interval)
        {
            for (int counter = 0; counter < (int) (duration/interval); counter++)
            {
                Dispatcher.Invoke(() => ChangeColor(Brushes.White));
                Thread.Sleep((int) (interval*1000));
                Dispatcher.Invoke(() => ChangeColor(Brushes.Red));
                Thread.Sleep((int) (interval*1000));
            }
        }

        public void ChangeColor(SolidColorBrush color)
        {
            MyTextBox.Background = color;
        }
    }
}

暫無
暫無

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

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