我希望我的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;
}此代码不会返回错误,但不会闪烁。
发布于 2013-11-29 23:54:02
首先,您不应该将Thread.Sleep放在您的主( UI )线程代码中,这会使UI线程进入睡眠状态,并且您不会看到UI上发生的任何更改。
就我个人而言,我将使用动画(在XAML中也是如此)和触发器/VisualState来实现您在这里尝试的内容。
但是,由于我对您的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();基本上,我从您的问题中翻译了以下代码片段:
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;发布于 2013-11-29 23:22:27
使用Timer对象,
下面是一个示例代码
private static System.Timers.Timer aTimer;
private static bool blinkFlag;
private Label label;
private void abilitaAltroToken(int indiceRiga,Grid grid)
{
UIElement element = grid.Children[indiceRiga];
label = (Label)element;
element = grid.Children[++indiceRiga];
TextBox textBox = (TextBox)element;
textBox.Background = Brushes.Blue;
label.Background = Brushes.Blue;
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 1 seconds (1000 milliseconds).
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
label.Background = (blinkFlag?Brushes.Blue:Brushes.White);
blinkFlag=!blinkFlag;
aTimer.Interval = 1000;
aTimer.Enabled = true;
}发布于 2013-11-29 23:22:02
你不应该在"UI-thread“中休眠。我建议您尝试使用DispatcherTimer。有关更多信息,请参阅以下链接:http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer%28v=vs.110%29.aspx
https://stackoverflow.com/questions/20288760
复制相似问题