如何让 wpf 工具包数据网格在绑定到数据集时显示新行

发布于 2024-08-11 17:26:27 字数 147 浏览 4 评论 0原文

有没有办法让 wpf 工具包 DataGrid 在绑定到 DataSet 时显示新行?换句话说,我有一个 DataGrid,我已将其 ItemsSource 设置为 DataTable,并且一切似乎都工作正常,除了我可以无法让网格显示我以编程方式添加到 DataTable 的行。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

琴流音 2024-08-18 17:26:27

您可以将 datagrid.ItemsSource 设置为 ObservableCollection

ObservableCollection<YourItem> items = new ObservableCollection<YourItem>();
yourDataGrid.ItemsSource = items;

然后,您应该能够添加到集合中以显示新行:

编辑:基于更新的信息。

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(...);
}

请参阅调度程序。所有 System.Windows.UserControl 对象都具有Dispatcher 属性。

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.

高跟鞋的旋律 2024-08-18 17:26:27

我不确定有人会如何解决这个问题,特别是因为我没有提到它,但问题是我正在从表单主线程之外的线程(即创建网格的线程)更新数据集在。您可以从另一个线程进行更新,但不能进行插入,尽管我不知道为什么。如果有人能阐明这一点,我将不胜感激。我的猜测是网格检查插入是否进入另一个线程,如果是,它会忽略它,因为这会导致异常。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文