Is there a way to get the wpf toolkit DataGrid
to show new rows when its bound to a DataSet
? In other words, I have a DataGrid
, I've set its ItemsSource
to a DataTable
, and everything seems to work fine, except I can't get the grid to show rows that I add to the DataTable
programatically.
问题:
回答1:
You can set the datagrid.ItemsSource
to an ObservableCollection<T>
.
ObservableCollection<YourItem> items = new ObservableCollection<YourItem>();
yourDataGrid.ItemsSource = items;
Then you should be able to just add to the collection to get the new rows to appear:
Edit: Based on updated info.
if (Dispatcher.CheckAcces())
{
// already on thread UI control was created on
items.Add(<your item>);
}
else
{
// update on same thread UI control was created on
// BeginInvoke would invoke a delegate which would call items.Add(<your item>)
Dispatcher.BeginInvoke(...);
}
See Dispatcher. All System.Windows.UserControl objects have a Dispatcher
property.
回答2:
I'm not sure how anyone would have figured this out, especially since I didn't mention it, but the problem was that I was updating the dataset from a thread other than the form's main thread, i.e. the thread that the grid was created on. You can do updates from another thread, but you can't do inserts, although I don't know why. If someone could shed some light on that, I'd appreciate it. My guess would be that the grid checks to see if the insert is coming in on another thread, and if so, it ignores it because that would cause an exception.