ItemsSource更改时更新Datagrid

时间:2013-01-15 23:11:34

标签: c# wpf timer wpfdatagrid

我已经通过很多论坛为我的问题找到了解决方案,但我找不到合适的解决方案。

我有一个Datagrid,它遵循MVVM模式绑定到Datasource(MS SQL Server 2008)。我已将ItemsSource绑定到ObservableCollection并实施了INotifyPropertyChanged界面。

我的数据库在特定时间限制内更改表值。现在,我想在我的UI中反映这个Datasource更改(即我希望我的UI ItemsSource得到更新)。当我想到这一点时,我明白我应该实现一个Timer概念(比如轮询),这样我的查询就会每15秒循环一次。

这是我的ViewModel Class,请指导我在哪里实施Timer Class ??

namespace MVVM_DemoAppl.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
 // Properties for the DispatcherTimer
  private bool disposed;
  private DispatcherTimer timer = new DispatcherTimer();
  // declaring instance of a class and Observable collection
  Model _myModel = new Model();
  private ObservableCollection<SystemStatus> _systemStatusData= new ObservableCollection<SystemStatus>();
  public ObservableCollection<SystemStatus> SystemStatusData
  {
    get { return _systemStatusData; }
    set
      {
        _systemStatusData= value;
      OnPropertyChanged("SystemStatusData");
      }
  }

public MainViewModel()
 {
   initializeload();
   timer.Tick += new EventHandler(timer_Tick);
   timer.Interval = new TimeSpan(0, 0, 15);
   timer.Start();
 }

 ~MainViewModel()
   {
       Dispose(false);
   }

  protected virtual void Dispose(bool disposing)
   {
       if (!disposed)
       {
           if (disposing)
           {
               timer.Stop();
               timer.Tick -= new EventHandler(timer_Tick);
           }
           disposed = true;
       }
   }

   private void timer_Tick(object sender, EventArgs e)
   {
       try
       {
           EventLogData.Clear();
           initializeload();
       }
       catch (Exception ex)
       {
           timer.Stop();
           Console.WriteLine(ex.Message);

       }
   }
private void initializeload()
{
   DataTable table = _myModel.getData();

 for (int i = 0; i < table.Rows.Count; ++i)
   SystemStatusData.Add(new SystemStatus
   {
Systems= table.Rows[i][0].ToString(),
Date =Convert.ToDateTime(table.Rows[i][1]),
Types = table.Rows[i][2].ToString(),
Messages = table.Rows[i][3].ToString(),
Critical = Convert.ToBoolean(table.Rows[i][1]),
    });
}

  public event PropertyChangedEventHandler PropertyChanged;

 private void OnPropertyChanged(string propertyname)
   {
     var handler = PropertyChanged;
     if (handler != null)
     handler(this, new PropertyChangedEventArgs(propertyname));
  }
 }

public class Model
 {
  string con = ConfigurationManager.AppSettings["ConnectionStrings"];
   public DataTable getData()
{
  DataTable ndt = new DataTable();
  SqlConnection sqlcon = new SqlConnection(con);
  sqlcon.Open();
  SqlDataAdapter da = new SqlDataAdapter("select top 5 System,Date,Typ,Message,Critical     from test_DB.dbo.SystemStatus",con);
  da.Fill(ndt);
  return ndt;
  }
 }
}

1 个答案:

答案 0 :(得分:3)

您可以使用DispatcherTimer。使您的ViewModel一次性使用并在处置时终止计时器。在构造函数中,配置计时器,将处理程序挂钩到Tick事件,然后启动它:

public MainViewModel()
{
    initializeload();
    timer.Tick += new EventHandler(timer_Tick);
    timer.Interval = new TimeSpan(0, 0, 15);
    timer.Start();
}
~MainViewModel()
{
    Dispose(false);
}
public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        if (disposing)
        {
            timer.Stop();
            timer.Tick -= new EventHandler(timer_Tick);
        }
        disposed = true;
    }
}

private void timer_Tick(object sender, EventArgs e)
{
    try 
    {
        SystemStatusData.Clear();
        initializeload();
    } 
    catch (...) 
    {
        // Problem best to stop the timer if there is an error...
        timer.Stop();
    }
}

private bool disposed;
private DispatcherTimer timer = new DispatcherTimer();