2013-02-01 57 views
1

我有一个函数叫做Checking()来更新我的用户界面。我想使这个函数AutoRun和它每秒运行它并更新我的UI。C#自动检查功能

我该怎么做?

这里是我的功能:

public MainWindow() 
{ 
    InitializeComponent(); 
    Checking() 
} 

public void Checking() 
{ 
    if (status= Good) 
     UI.color.fill= Green 
    else 
     UI.color.Fill = Red 
} 
+0

为什么不只是绑定到'status'属性(或对变化事件作出反应)? –

+0

这段代码没有做任何事情,比如你正在尝试做什么......你有没有使用过Timer或Background Worker等等。在Initialize之后,你调用'Checking()'你在调用Method之后使用了什么初始化..? – MethodMan

回答

0

你要确保在检查()所做的更改绑定和IPropertyNotifyChange发送它。

using System.Reactive; 
public MainWindow() 
{ 
    InitializeComponent(); 
    Observable.Interval(TimeSpan.FromSeconds(1)) 
     .Subscribe(_ => Checking()); 
} 
+0

我认为Observable.Interval和System.Reactive不支持WPF,我无法找到任何其他类似方法的引用? – PublicAffair

+0

@PublicAffair我今天用WPF使用它们。您可能只需要将程序集添加到项目引用集。 – kenny

+0

@PublicAffair如果你还没有使用VS12,它看起来像你需要下载或nuget它。 http://msdn.microsoft.com/en-us/data/gg577610.aspx – kenny

1

此代码可以帮助您

//need to add System.Timers in usings 
using System.Timers; 

//inside you code 
//create timer with interval 2 sec 
Timer timer=new Timer(2000); 
//add eventhandler 
timer.Elapsed+=new ElapsedEventHandler(timer_Elapsed); 
//start timer 
timer.Start(); 


private void timer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     MessageBox.Show("324"); 
     //or other actions 
    } 
0

DispathTimer是计时器,在一个线程与UI工作。此代码可以帮助您

public partial class MainWindow : Window { 
    public MainWindow() { 
     InitializeComponent(); 

     DispatcherTimer timer = new DispatcherTimer(){Interval = new TimeSpan(0,0,0,1)}; 
     timer.Tick += new EventHandler(timer_Tick); 
     timer.Start(); 
    } 

    void timer_Tick(object sender, EventArgs e) { 
     Checking(); 
    } 

    public void Checking() 
    { 
     ..... 
    } 
+0

唯一的问题是我的Checking()与Serialport通信!并在同一时间其他功能做同样的事情,所以这个自动功能导致我的程序崩溃...我不知道我怎么能解决这个问题! – PublicAffair

+0

@PublicAffair可能应该同步一些常用数据吗? – hvost239