WPF DataGrid 如何在 ItemsSource 更新时获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1107062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:42:37  来源:igfitidea点击:

WPF DataGrid how to get when ItemsSource updates

wpfeventsdatagridviewwpf-controlswpfdatagrid

提问by iLemming

Which event fires when DataGrid's source is updating? I've tried DataContextChanged and SourceUpdated but it never worked out.

当 DataGrid 的源更新时会触发哪个事件?我试过 DataContextChanged 和 SourceUpdated 但它从来没有奏效。

Actually I need a simple thing. I want, if there is a new row comes, scroll the GridView's scrollbar down to the bottom to see what it was.

其实我需要一个简单的东西。我想要,如果有新行出现,将 GridView 的滚动条向下滚动到底部以查看它是什么。

回答by Nidal Valot

I had the same problem and I manage it this way

我有同样的问题,我是这样管理的

DataGrid myGrid = new DataGrid();
CollectionView myCollectionView = (CollectionView)CollectionViewSource.GetDefaultView(myGrid.Items);
((INotifyCollectionChanged)myCollectionView).CollectionChanged += new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged);

You then need to implement the logic in the event handler DataGrid_CollectionChanged.

然后您需要在事件处理程序中实现逻辑DataGrid_CollectionChanged

回答by rams

Set NotifyOnTargetUpdated = true for the ItemsSource binding and handle TargetUpdated event. If you've multiple bindings, then look for DataTransferEventArgs Property to find out if the target is ItemsSource or not.

为 ItemsSource 绑定设置 NotifyOnTargetUpdated = true 并处理 TargetUpdated 事件。如果您有多个绑定,则查找 DataTransferEventArgs 属性以确定目标是否为 ItemsSource。

回答by Cody C

If you are trying to have the grid refresh when something is added to the database itself, that's not going to happen. I'm more familiar with WinForms than WPF but I'm assuming there is no magical way to keep a grid in sync with the database without writing some background process that continuously checks for database changes.

如果您尝试在将某些内容添加到数据库本身时刷新网格,则不会发生这种情况。我对 WinForms 比 WPF 更熟悉,但我假设没有神奇的方法可以使网格与数据库保持同步,而无需编写一些持续检查数据库更改的后台进程。

If you are updating the actual data source of the grid (ex. Collection) then that will update the grid.

如果您正在更新网格的实际数据源(例如集合),那么这将更新网格。

回答by Osin Toumani

For my part i've used SelectionChange notification which raise each event Del/Add/Edit/Select It's work very well

就我而言,我使用了 SelectionChange 通知,它引发了每个事件 Del/Add/Edit/Select 它工作得很好

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Console.WriteLine("hi");
}