Keeping a GridView up to date in WPF
I'm a .Net developer moving from Winforms to WPF and have run into a common issue where I would like to find a WPF specific solution. I have a GridView which is basically bound to a table in SQL. I happen to be using MVVM, so this is done indirectly, with the GridView actually being bound to a ViewModel that gets its data from an Entity Model. In Winforms, to keep this synched in somewhat real-time, I would have a background thread that would search for an update every so often and get the latest version of t开发者_StackOverflow中文版he SQL table data. Of course, I could do this in WPF, but I was wondering if there is a better way to do this in WPF where the UI can truly update in "real-time" as the table is updated. The app will be on many machines, so I cannot simply get an update when the local user changes the data in some way through the app. Refresh buttons are terrible, so I do not want that either. Is there a best practice for this in WPF?
The polling methodology is still sound. As far as "better" way, there are methods of setting up notifications (query change notification for example) in ADO.NET with SQL 2005 or newer. This is not a WPF specific implementation, however, and can be applied to windows forms.
tbh, I'd do it rather similar, i.e. a background thread that polls, then update the bound collection. If you want a duplex communication, you could do that o avoid polling but it brings its own issues and hasn't got anything to do with WPF. A few things tokeep in mind:
- Use an ObservableCollection as ItemsSource. That way you can feed in "deltas" of what has changed which should keep server communication to a minimum.
- Use the Dispatcher.Invoke when you modify the ObservableCollection from the background, otherwise...you know the problems from WinForms.
精彩评论