WPF: Raise an Event when Item is added in ListView

后端 未结 2 1858
南旧
南旧 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.

    0 讨论(0)
  • 2021-02-05 08:36

    Note: This solution was meant for a WinForms ListView.

    In my case I ended up coming to a fork in the road with 2 choices...

    (1) Create a custom ListView control that inherits a ListView's class. Then add a new event to be raised when any item is added, deleted, or ListView is cleared. This path seemed really messy and long. Not to mention the other big issue that I would need to replace all my original ListViews with the newly created Custom ListView control. So I passed on this!


    (2) With every add, delete, or clear call to the listview I also called another function simulating the CollectionChanged event.

    Create the new event like function...

    private void myListViewControl_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        //The projects ListView has been changed
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                MessageBox.Show("An Item Has Been Added To The ListView!");
                break;
            case NotifyCollectionChangedAction.Reset:
                MessageBox.Show("The ListView Has Been Cleared!");
                break;
        }
    }
    

    Add an item to the ListView elsewhere...

    ListViewItem lvi = new ListViewItem("ListViewItem 1");
    lvi.SubItems.Add("My Subitem 1");
    myListViewControl.Items.Add(lvi);
    myListViewControl_CollectionChanged(myListViewControl, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, lvi, lvi.Index));
    

    Clear the ListView elsewhere...

    myListViewControl.Items.Clear();
    myListViewControl_CollectionChanged(myListViewControl, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    
    0 讨论(0)
提交回复
热议问题