WPF:当项目在ListView中添加触发事件 [英] WPF: Raise an Event when Item is added in ListView
问题描述
我工作的WPF和我使用一个ListView,我需要当一个项目被添加到它来触发一个事件。我曾尝试这样的:
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();
}
不过,这似乎是工作,只有当整个集合改变了,我看了这篇文章:<一href=\"http://stackoverflow.com/questions/5904519/event-fired-when-item-is-added-to-listview\">event-fired-when-item-is-added-to-listview,但最好的答案适用于只有一个列表框。我试图改变code到ListView的,但我不是能够做到这一点。
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.
推荐答案
的注意一个WPF列表视图这只是工程!的
经过一番研究,我已经找到了答案,我的问题,这真的很容易:
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]);
}
}
其实, NotifyCollectionChangedAction
枚举允许程序通知你有关的任何变化,如:添加,移动,替换,删除和重置
Actually, the NotifyCollectionChangedAction
enum allows your program to inform you about any change such as: Add, Move, Replace, Remove and Reset.
这篇关于WPF:当项目在ListView中添加触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!