wpf - Alerting User By Changing Background of Control C#


Keywords:c# 


Question: 

I'm programming in WPF(C#). I want to alert users about filling empty text box (or any other controls). I want to flash control to alert him/her. This is the codes that I used them but it does not change color:

static void AlertByChangingBackground(Control control)
{
    Action a = () =>
    {
        control.Background = System.Windows.Media.Brushes.Red;
        Thread.Sleep(500);
        control.Background = System.Windows.Media.Brushes.White;
    };

    control.Dispatcher.Invoke(a);
} 

As it can be seen, I also use Action but it does not work. I also use control.UpdateLayout() before Sleep method but it does not working, too. How can I fix the problem.

Update 1:

Now, I use codes illustrated below. But the problem is when the function is called several times (specially when it is called continuously in short times) the color of text does not back to its first color. For example my control may be remain at red color. How can I fix it?

public static void AlertByChangingBackground(Control control)
{
    Action a = () =>
    {
        ColorAnimation animation;
        animation = new ColorAnimation();

        animation.From = Colors.Red;
        animation.To = ToColor(control.Background);
        animation.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 330));

        RepeatBehavior rb = new RepeatBehavior(3);
        animation.RepeatBehavior = rb;
        control.Background = new SolidColorBrush(Colors.Red);
        control.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
    };

    control.Dispatcher.BeginInvoke(a);
}

I note that I want to start animation from current background of my control, not from white or any predefined color.


1 Answer: 

You can use triggers or animations to alert the user rather than using thread,

you can add xmlns:sys="clr-namespace:System;assembly=mscorlib" namespace for checking the string is empty or not.

<Style TargetType="{x:Type TextBox}" x:Key="AlertStyle">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Mode=Self}}" Value="{x:Static sys:String.Empty}">
                <Setter Property="Background" Value="Red"></Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>

use this style for your TextBox control like follows,

  <TextBox Width="100" Height="25" Style="{StaticResource AlertStyle}">