如何在WPF中刷新ListView

35

你好,我正在使用WPF,并逐一向listview.ItemsSource添加记录。只有在所有数据都包含的情况下,我的数据才会出现,但是我希望能够逐一添加时即时显示数据。

我尝试使用ListView.Item.Refresh(),但它没有起作用。

是否有其他方法呢?


我不太确定我理解你的问题。你想让你的项目在列表视图中一个接一个地出现吗?添加项目非常快,所以你可能甚至都不会注意到。 - Botz3000
6个回答

50

如果您仍需要在其他情况下刷新您的ListView(假设您需要在将所有元素添加到ItemsSource之后更新它一次),那么您应该使用以下方法:

ICollectionView view = CollectionViewSource.GetDefaultView(ItemsSource);
view.Refresh();

31

例子:

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

7
您需要绑定到实现了INotifyCollectionChanged接口的集合,例如ObservableCollection<T>。这个接口会在添加或删除项时通知绑定的控件(所以您不需要进行任何调用)。
链接到 INotifyCollectionChanged 接口 此外,System.Windows.Controls.ListView没有名为 Item 的成员,请确保您没有试图从System.Windows.Forms.ListView的成员中调用方法。 参考: MSDN

2

@decyclone:

我正在使用WPF开发,想要实现一个树形视图,可以动态添加和删除文件。使用ObservableCollection方法可以添加(通过拖放和打开文件对话框)。

添加功能已经正常,但是删除功能无法正确显示。刷新方法并没有“刷新”。解决方案是重新设置listview.ItemSource为新的值(即不包含已删除元素的列表)。


1
    ObservableCollection<int> items = new ObservableCollection<int>();
    lvUsers.ItemsSource = items;

    for (int i = 0; i < 100; i++)
    {
        items.Add(i);
    }            

无需刷新


0
我正在做这件事:
ObservableCollection<int> items = new ObservableCollection<int>();
lvUsers.ItemsSource = items;

for (int i = 0; i < 100; i++)
{
    items.Add(i);
} 

但是数据直到我调整窗口大小后才出现在列表中。:(


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接