2017-02-23 15 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}">