WPF Datagrid SelectionChanged 事件在加载行时多次触发

发布于 2024-09-20 00:00:22 字数 142 浏览 6 评论 0原文

当我在 WPF DataGrid 中使用 DataGridComboBoxColumn 时,在加载 WPF DataGrid 中的行时,DataGrid SelectionChanged 事件会根据行数触发多次。

我怎样才能阻止这个?因此我面临性能问题。

When i use DataGridComboBoxColumn in my WPF DataGrid, the DataGrid SelectionChanged event is triggering multiple times based on the number of rows while loading the rows in the WPF DataGrid.

How can i stop this? Because of this I am facing Performance issue.

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

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

发布评论

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

评论(1

不知所踪 2024-09-27 00:00:26

这完全取决于您如何设置绑定。

例如,如果您有一个 ObservableCollection,并且在加载数据时向其中添加项目,则可能会遇到此类问题。有多种解决方案,但我宁愿查明问题,也不愿输入数公里长的文本,因此,如果您可以提供更多详细信息,我将回复我对解决方案的最佳猜测。

编辑:看到示例后,我发现了问题所在:DataGrid 中有一个 DataGridComboBoxColumn,其中 SelectedValue 绑定到属性;当执行绑定时,将触发 ComboBox 的 SelectionChanged 事件,并由 DataGrid 上的处理程序捕获。有几个选项可以防止这种情况......一个是检查 EventHandler 中的 OriginalSource,另一个是处理 ComboBox 上的事件并将其 Handled 属性设置为 true,这样它就不会被 DataGrid 处理程序捕获以及。

另一种更好的解决方案是不在代码隐藏中处理选择事件,除非有非常充分的理由。最好将 DataGrid 的 ItemsSource 绑定到代表原始集合的 ICollectionView(例如 ListCollectionView); ICollectionView 的 CurrentItem 自动与 DataGrid 中选定的行同步,并且您可以处理 ICollectionView 上的选择更改事件,使其变得更加容易(并且可进行单元测试,与 UI 实现有些分离等)。这不适用于多个选择,但如果一次只能选择一行,它应该可以很好地工作。

It depends on exactly how you have your bindings set up.

If for instance you have an ObservableCollection and you add items to it when you load data, you might run into this kind of problem. There are multiple solutions but I'd rather pinpoint the problem than typing kilometers of text, so if you can provide a bit more details I'll reply with my best guess at a solution.

Edit: After seeing the sample I figured out what the problem is: there's a DataGridComboBoxColumn in the DataGrid, with a SelectedValue binding to a property; when the binding is executed, the SelectionChanged event of the ComboBox is fired, and is caught by the handler on the DataGrid. There are several options to prevent this... one is to check the OriginalSource in the EventHandler, and the other is to handle the event on the ComboBox and to set its Handled property to true so it doesn't get caught by the DataGrid handler as well.

An alternative, much better solution would be to not handle the selection events in the code-behind unless there's a very solid reason. It's best to bind the ItemsSource of the DataGrid to an ICollectionView (ListCollectionView for example) which represents the original collection; the ICollectionView's CurrentItem is automatically synchronized with the selected row in the DataGrid and you can handle selection changed events on the ICollectionView, making it much easier (and unit-testable, somewhat separate from the UI implementation etc.). This doesn't work with multiple selections, but if you can only select a single row at a time it should work quite well.

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