当ItemsSource更改时更新Datagrid

本文关键字:更新 Datagrid ItemsSource | 更新日期: 2023-09-27 17:53:39

我已经浏览了许多论坛来寻找解决我的问题的方法,但我没有找到合适的解决方案。

我有一个Datagrid,绑定到Datasource (MS SQL Server 2008)遵循MVVM模式。我已经将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;
  }
 }
}

当ItemsSource更改时更新Datagrid

您可以使用DispatcherTimer。将ViewModel设置为可丢弃的,并在dispose时杀死计时器。在构造函数中,配置计时器,将处理程序挂接到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();