WPF:在ListView中添加项目时提高事件 [英] WPF: Raise an Event when Item is added in ListView

查看:98
本文介绍了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中添加项目时提高事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆