2011-04-01 30 views
3

我有一些代码执行并获取执行的返回值。 我将此值设置为我的窗口的依赖项属性,因为有样式触发器绑定到它。 当变量为0时,它使用默认样式,1为淡红色样式,2为淡绿色时。在WPF延迟后复位变量的值

但我必须在一段时间后以某种实用的方式重置这种风格。

什么是最简单的方法来做到这一点?

if (!Compiler.TryCompile(strText, Models[Model], EntryPoint.Text, out error)) 
{ 
    output.Items.Add("Error compiling:"); 
    output.Items.Add(error); 
    CompilationStatus = 1; // dependency property bound on ui 
} 
else { 
    output.Items.Add("Compilation successful!"); 
    CompilationStatus = 2; // dependency property bound on ui 
} 

// should execute this after 5 seconds 
CompilationStatus = 0; // dependency property bound on ui 

WPF和.net 4在项目中使用。 谢谢!

回答

0

如果时间精确不是一个问题,因为你正在使用WPF和.Net 4,这是一个很容易的,只需用下面的代替你的代码:

new Task(delegate() { 
    Thread.Sleep(5000); 
    Dispatcher.Invoke((Action)delegate(){ 
    CompilationStatus = 0; 
    }); 
}).Start(); 

它将调用的UI穿过调度员,所以你应该是安全的。

这个Fire @ Forget方法不是非常精确,如果CPU处于压力下,可能会滞后。如果这对你没有帮助,那么你应该使用System.Diagnostics中的Stopwatch类。

1

我通常使用自定义扩展方法是:

public static class DispatcherHelper 
{ 
    public static void DelayInvoke(this Dispatcher dispatcher, TimeSpan ts, Action action) 
    { 
     DispatcherTimer delayTimer = new DispatcherTimer(DispatcherPriority.Send, dispatcher); 
     delayTimer.Interval = ts; 
     delayTimer.Tick += (s, e) => 
     { 
      delayTimer.Stop(); 
      action(); 
     }; 
     delayTimer.Start(); 
    } 
} 

在你的情况,你可以使用它像这样:

Dispatcher.DelayInvoke(TimeSpan.FromSeconds(5),() => 
{ 
    CompilationStatus = 0; 
} 

编辑:我已经忘记了,但看起来这种方法最初是由Jon Skeet在这个SO线程中撰写的:Delayed Dispatch Invoke?