WPF:在ListView中添加项目时提高事件

编程入门 行业动态 更新时间:2024-10-26 22:28:54
本文介绍了WPF:在ListView中添加项目时提高事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在使用WPF,而且我正在使用ListView,当我添加一个项目时,我需要触发一个事件。我已经尝试过:

var dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty,typeof(ListView)); if(dependencyPropertyDescriptor!= null) { dependencyPropertyDescriptor.AddValueChanged(this,ItemsSourcePropertyChangedCallback); }

.....

private void ItemsSourcePropertyChangedCallback(object sender,EventArgs e) { RaiseItemsSourcePropertyChangedEvent(); }

但是,只有当整个集合更改时,阅读这篇文章:事件触发 - when-item-is-added- to-listview ,但最佳答案仅适用于列表框。我试图将代码更改为ListView,但我无法做到这一点。

希望你能帮助我。谢谢你提前。

解决方案

注意这只适用于WPF Listview!

经过一些研究,我找到了我的问题的答案,这很简单:

public MyControl() { InitializeComponent(); ((INotifyCollectionChanged)listView.Items).CollectionChanged + = ListView_CollectionChanged; } private void ListView_CollectionChanged(object sender,NotifyCollectionChangedEventArgs e) { if(e.Action == NotifyCollectionChangedAction.Add) { //将新项目滚动到视图 listView.ScrollIntoView(e.NewItems [0]); } }

其实, NotifyCollectionChangedAction 枚举允许您的程序通知您有任何更改,如:添加,移动,替换,删除和重置。

I am working on WPF and I am using a ListView, and I need to fire an event when an item is added to it. I have tried this:

var dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ListView)); if (dependencyPropertyDescriptor != null) { dependencyPropertyDescriptor.AddValueChanged(this, ItemsSourcePropertyChangedCallback); }

.....

private void ItemsSourcePropertyChangedCallback(object sender, EventArgs e) { RaiseItemsSourcePropertyChangedEvent(); }

But It seems to be working only when the entire collection is changed, I have read this post: event-fired-when-item-is-added-to-listview, but the best answer applies for a listBox only. I tried to change the code to ListView but I wasnt able to do that.

I hope You can help me. Thank you in advance.

解决方案

Note this only works for a WPF Listview!

After some research I have found the answer to my question and It's really easy:

public MyControl() { InitializeComponent(); ((INotifyCollectionChanged)listView.Items).CollectionChanged += ListView_CollectionChanged; } private void ListView_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { // scroll the new item into view listView.ScrollIntoView(e.NewItems[0]); } }

Actually, the NotifyCollectionChangedAction enum allows your program to inform you about any change such as: Add, Move, Replace, Remove and Reset.

更多推荐

WPF:在ListView中添加项目时提高事件

本文发布于:2023-11-10 22:57:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   项目   WPF   ListView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!