Reputation: 2965
I have a DataGrid
in C# WPF
that is filled with Employees
. Essentially I need to read from a Database
periodically as when the Employees
enter a building, a field is modified. I am having a few issues with the best way to approach this situation. First, this is how I define my 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();
}
Essentially the TimerTick
method that currently fires every second simply calls this method again, so that the entire table is retrieved from the database and the appropriate fields (whether the user is in the building or not is updated).
This method as I said has a number of issues. Firstly, it doesn't look good. As the DataGrid
is constantly refreshing, any actions that the user takes on the grid is slow and the highlighting of each row is distorted.
Secondly I use methods to filter the DataGrid
. The user is able to type in a name of an Employee
and the DataGrid
is filtered accordingly. Once again because the DataGrid
is refreshed every second, it is literally impossible to filter on the DataGrid
because everything the user types is undone every second.
I understand I could potentially refresh the DataGrid
say every minute which would be much improved, however it is still no where near ideal and I am sure there is a better solution. How can I improve this solution so that the updating of the DataGrid
is a lot more subtle and unknown to the user?
Upvotes: 1
Views: 671
Reputation: 2977
Instead of updating the whole collection, only add, move or remove items from the ObservableCollection
that are actually different or changed. It implements INotifyCollectionChanged
and INotifyPropertyChanged
which will notify the DataGrid.
Upvotes: 1