WPF: Raise an Event when Item is added in ListView

后端 未结 2 1856
南旧
南旧 2021-02-05 08:12

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 = Dep         


        
2条回答
  •  野性不改
    2021-02-05 08:32

    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.

提交回复
热议问题