C#如何使TextBox闪烁

bir*_*tri 0 c# wpf textbox

我想让我TextBox间歇性地眨眼.

我有这个方法

private void abilitaAltroToken(int indiceRiga, Grid grid)
{
    UIElement element = grid.Children[indiceRiga];
    Label label = (Label)element;
    element = grid.Children[++indiceRiga];
    TextBox textBox = (TextBox)element;
    textBox.Background = Brushes.Blue;
    label.Background = Brushes.Blue;

    Thread.Sleep(1000);
    label.Background = Brushes.White;

    Thread.Sleep(1000);
    label.Background = Brushes.Blue;

    Thread.Sleep(1000);
    label.Background = Brushes.White;

    Thread.Sleep(1000);
    label.Background = Brushes.Blue;       
}
Run Code Online (Sandbox Code Playgroud)

此代码不会返回错误,但不会发生闪烁.

sth*_*ura 5

首先,您不应该将Thread.Sleep放在您的Main(UI)线程代码中,这将使UI线程处于休眠状态,并且您不会在UI上看到任何更改.

就个人而言,我会使用动画(在XAML中也是如此)和Triggers/VisualStates来实现你在这里尝试的东西.

但是,由于我对XAML的了解不多,以下是实现标签闪烁的程序代码:

var colorAnim = new ColorAnimationUsingKeyFrames()
{
    KeyFrames = new ColorKeyFrameCollection
            {
                new DiscreteColorKeyFrame(Colors.White, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.5))),
                new DiscreteColorKeyFrame(Colors.Blue, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1))),
                new DiscreteColorKeyFrame(Colors.White, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1.5))),
                new DiscreteColorKeyFrame(Colors.Blue, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2))),
            }
};

var storyBoard = new Storyboard();

storyBoard.Children.Add(colorAnim);
Storyboard.SetTarget(storyBoard, label);
Storyboard.SetTargetProperty(storyBoard, new PropertyPath("(Background).(SolidColorBrush.Color)"));

storyBoard.Begin();
Run Code Online (Sandbox Code Playgroud)

基本上,我从您的问题中翻译了以下代码段:

Thread.Sleep(1000);  
label.Background = Brushes.White;

Thread.Sleep(1000);  
label.Background = Brushes.Blue;

Thread.Sleep(1000);  
label.Background = Brushes.White;

Thread.Sleep(1000);  
label.Background = Brushes.Blue;
Run Code Online (Sandbox Code Playgroud)