我已经通过许多论坛为我的问题找到解决方案,但我没有找到合适的解决方案。
我有一个遵循 MVVM 模式Datagrid
的绑定到(MS SQL Server 2008)。Datasource
我已经绑定ItemsSource
到一个ObservableCollection
并实现了INotifyPropertyChanged
接口。
我的数据库在特定时间限制内更改表值。现在,我想Datasource
在我的 UI 中反映这种变化(即我希望看到我的 UIItemsSource
得到更新)。当我想到这一点时,我明白我应该实现一个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;
}
}
}