2017-02-23 50 views
-1

我在WPF(C#)中编程。我想提醒用户填写空文本框(或任何其他控件)。我想闪光控制提醒他/她。这是我用他们的代码,但它不会改变颜色:通过更改控制背景C提醒用户#

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

如可以看出,我也用Action但它不工作。我也在Sleep方法之前使用control.UpdateLayout(),但它也不起作用。我该如何解决这个问题。

更新1:

现在,我使用下面示出的代码。但问题在于函数被多次调用时(特别是在短时间内连续调用函数时)文本的颜色不会回到其第一种颜色。例如,我的控件可能会保持红色。我该如何解决它?

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

我注意到,我想从我的控制当前的背景,而不是白色或者任何预定义的颜色开始动画。

+3

你应该看看[动画](http://stackoverflow.com/q/14158500/5246145),而不是试图冻结线程的执行。 – 3615

+0

@ 3615谢谢,为什么不把你的文本复制为答案?我想接受你的方法作为我的答案。 –

+0

对不起,我没有时间给你一个完整的答案,这就是为什么我只是评论。我很高兴它帮助你:) – 3615

回答

0

可以使用触发器或动画来提醒用户,而不是使用线程,

您可以添加的xmlns:SYS =“CLR的命名空间:系统;装配= mscorlib程序”以检查串命名空间为空或不。

<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> 

使用这种风格为您的TextBox控件类似如下,

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