Event fired when item is added to ListView?

后端 未结 2 435
一向
一向 2021-01-13 08:21

I have this XAML:



        
2条回答
  •  甜味超标
    2021-01-13 09:13

    You can subscribe to the ItemsChanged event on your listbox.Items property. This is a little tricky because you have to cast it first. The code to subscribe would look like this:

    ((INotifyCollectionChanged)MainListBox.Items).CollectionChanged +=  ListBox_CollectionChanged;
    

    And then inside that event you can get to your item with code like this:

    private void ListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems.Count > 0)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    var newListItem = MainListBox.ItemContainerGenerator.ContainerFromItem(e.NewItems[0]) as Control;
                    if (newListItem != null)
                    {
                        newListItem.Background = System.Windows.Media.Brushes.Red;
                    }
                }, DispatcherPriority.SystemIdle);
            }
        }
    

提交回复
热议问题