你好,我正在使用WPF,并逐一向listview.ItemsSource添加记录。只有在所有数据都包含的情况下,我的数据才会出现,但是我希望能够逐一添加时即时显示数据。
我尝试使用ListView.Item.Refresh(),但它没有起作用。
是否有其他方法呢?
如果您仍需要在其他情况下刷新您的ListView(假设您需要在将所有元素添加到ItemsSource之后更新它一次),那么您应该使用以下方法:
ICollectionView view = CollectionViewSource.GetDefaultView(ItemsSource);
view.Refresh();
// 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>.
INotifyCollectionChanged
接口的集合,例如ObservableCollection<T>
。这个接口会在添加或删除项时通知绑定的控件(所以您不需要进行任何调用)。System.Windows.Controls.ListView
没有名为 Item 的成员,请确保您没有试图从System.Windows.Forms.ListView
的成员中调用方法。
参考: MSDN
@decyclone:
我正在使用WPF开发,想要实现一个树形视图,可以动态添加和删除文件。使用ObservableCollection
方法可以添加(通过拖放和打开文件对话框)。
添加功能已经正常,但是删除功能无法正确显示。刷新方法并没有“刷新”。解决方案是重新设置listview.ItemSource
为新的值(即不包含已删除元素的列表)。
ObservableCollection<int> items = new ObservableCollection<int>();
lvUsers.ItemsSource = items;
for (int i = 0; i < 100; i++)
{
items.Add(i);
}
无需刷新
ObservableCollection<int> items = new ObservableCollection<int>();
lvUsers.ItemsSource = items;
for (int i = 0; i < 100; i++)
{
items.Add(i);
}
但是数据直到我调整窗口大小后才出现在列表中。:(