【发布时间】:2016-03-30 20:07:40
【问题描述】:
我在 C# WPF 中有一个 DataGrid,其中填充了 Employees。本质上,我需要定期从Database 读取,因为当Employees 进入建筑物时,会修改一个字段。我在处理这种情况的最佳方法方面遇到了一些问题。首先,这就是我定义我的DataGrid的方式;
public ICollectionView FilteredView { get; set; }
public ObservableCollection<EmployeeModel> Employees {get; set; }
private void OnPageLoad(object sender, RoutedEventArgs e)
{
var _employeeDataService = new EmployeeDataService();
Employees = _employeeDataService.HandleEmployeeSelect();
FilteredView = CollectionViewSource.GetDefaultView(Employees);
dataGrid.ItemsSource = FilteredView;
DataContext = this;
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(TimerTick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
本质上,当前每秒触发一次的TimerTick 方法只是再次调用此方法,以便从数据库中检索整个表并更新相应的字段(无论用户是否在建筑物中)。
正如我所说的这种方法有很多问题。首先,它看起来不太好。由于DataGrid 不断刷新,用户在网格上执行的任何操作都很慢,并且每一行的突出显示都会失真。
其次,我使用方法来过滤DataGrid。用户可以输入Employee 的名称,DataGrid 会被相应地过滤。再一次,因为 DataGrid 每秒刷新一次,实际上不可能过滤 DataGrid,因为用户键入的所有内容每秒都被撤消。
我知道我可能会每分钟刷新一次DataGrid,这会得到很大改善,但它仍然远非理想,我相信有更好的解决方案。我该如何改进这个解决方案,使DataGrid 的更新对用户来说更加微妙和未知?
【问题讨论】:
-
问题:为什么要经常刷新DataGrid?您是否只是每秒更新属性或重新设置视图的数据上下文?
-
我的建议是您不能从数据库中获取所有数据。首先检查数据库中是否发生任何更改。如果该函数为真,则不仅仅是从数据库中获取数据。 (使用线程获取数据)
-
@VivekSaurav 它基本上是一个监控员工何时进入/离开建筑物的系统。目前我正在重置数据上下文,但我想目的是避免这种情况
-
@JobyJames “首先检查数据库中是否发生了任何更改。”如何实现这一目标?
标签: c# wpf xaml timer datagrid