How I Can Refresh ListView in WPF

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>.

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();

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


@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).

Tags:

Wpf

Listview