How I Can Refresh ListView in WPF

后端 未结 5 443
死守一世寂寞
死守一世寂寞 2020-12-05 17:37

Hi I am using WPF and adding records one by one to the listview.ItemsSource. My data will appear when all the data is included, but I want to show the data as it is added o

相关标签:
5条回答
  • 2020-12-05 18:21

    If you still need to refresh your ListView in any other case (lets assume that you need to update it ONE time after ALL the elements were added to the ItemsSource) so you should use this approach:

    ICollectionView view = CollectionViewSource.GetDefaultView(ItemsSource);
    view.Refresh();
    
    0 讨论(0)
  • 2020-12-05 18:23

    Example:

    // Create a collection of Type System.Collections.ObjectModel.ObservableCollection<T>
    // Here T can be anything but for this example, we use System.String
    ObservableCollection<String> names = new ObservableCollection<String>();
    
    // Assign this collection to ItemsSource property of ListView
    ListView1.ItemsSource = names;
    
    // Start adding items to the collection
    // They automatically get added to ListView without a need to write any extra code
    names.Add("Name 1");
    names.Add("Name 2");
    names.Add("Name 3");
    names.Add("Name 4");
    names.Add("Name 5");
    
    // No need to call ListView1.Items.Refresh() when you use ObservableCollection<T>.
    
    0 讨论(0)
  • 2020-12-05 18:24
        ObservableCollection<int> items = new ObservableCollection<int>();
        lvUsers.ItemsSource = items;
    
        for (int i = 0; i < 100; i++)
        {
            items.Add(i);
        }            
    

    No need refresh

    0 讨论(0)
  • 2020-12-05 18:38

    You need to bind to a collection which implements INotifyCollectionChanged, for example ObservableCollection<T>. This interface notifies the bound control whenever an item is added or removed (so you don't have to make any call at all).

    Link to INotifyCollectionChanged Interface

    Also System.Windows.Controls.ListView doesn't have a member named Item, make sure you are not trying to call a method on a member from System.Windows.Forms.ListView. Reference: MSDN

    0 讨论(0)
  • 2020-12-05 18:41

    @decyclone:

    I'm working in WPF the idea is to have a tree view that we can dynamically add and remove elements - files. The ObservableCollection was the method for adding (using drag and drop and an open dialog box for files)

    ObservableCollection worked fine for adding but items removal was not being displayed correctly. The refresh method did not "refresh". The solution was to reset (again) the listview.ItemSource to the new values (the list without the elements that were removed).

    0 讨论(0)
提交回复
热议问题