简体   繁体   中英

WPF Datagrid ItemSource + ObservableCollection

I've a Datagrid that shows all the Data from an ObservableCollection.But I just want to show the first 10 elements in the Datagrid. Can you please help?

Let's say your DataGrid is dg. You can try :

int nbV = 10; //number you want
ItemCollection ic = new ItemCollection();
for(int k = 0; k < nbV; k++)
   {
      ic.Add(dg.Items[k]);
   }

dg.ItemsSource = ic.DefaultView;

I assume you are using MVVM.. You can try using collection view source..

 observableCollection = new ObservableCollection<string>();
 Items = CollectionViewSource.GetDefaultView(observableCollection.Take(10));

Where "Items" is property in your viewmodel and "ItemsSource" for your data grid..

public ICollectionView Items { get; set; }

You may have to include couple of namespaces in your viewmodel

using System.Collections.ObjectModel;
using System.Windows.Data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM