c# - How to limit the number of items from an observablecollection databinded listbox? -
here how goes. have viewmodel call webclient , populate observable collection items. need have 2 different listboxes in 2 different pages same itemssource viewmodel. how can limit number of items in 1 of 2 listboxes without affect other? tried use .take(limit) viewmodel items being created affects both listboxes.
update
the viewmodel
public class mainviewmodel : inotifypropertychanged { public mainviewmodel() { this.items = new observablecollection<itemviewmodel>(); this.mainlist = new collectionviewsource(); } public observablecollection<itemviewmodel> items { get; private set; } public collectionviewsource mainlist { get; set; } void client_downloadstringcompleted(object sender, downloadstringcompletedeventargs e) { try { ............... //ignore dummy data in foreach loop. showcase. foreach (var item in items) { //items creation this.items.add(new itemviewmodel() { lineone = item }); } this.mainlist.source = app.viewmodel.items; this.mainlist.filter += (s, a) => a.accepted = app.viewmodel.items.indexof((itemviewmodel)a.item) < 10; } catch (exception ex) { messagebox.show(ex.message); } } ..................... }
on view's side
public mainpage() { initializecomponent(); datacontext = app.viewmodel; list.itemssource = app.viewmodel.mainlist.view; }
update 2
another option found (without using collectionviewsource
) make new public observablecollection<itemviewmodel> mainlist { get; private set; }
, use 1 more
foreach (var item in items.take(limit)) { //items creation this.mainlist.add(new itemviewmodel() { lineone = item }); }
in order populate observablecollection , bind listbox mainlist. working think poor practice because in way have duplicated data. ideas on that?
you use collectionviewsource , add filtering logic limit number of items shown. example, if wanted show 100 items:
var cvs = new collectionviewsource(); cvs.source = mylist; //the raw list viewmodel cvs.filter += (s, a) => a.accepted = mylist.indexof(a.item) < 100; listbox2.itemssource = cvs.view;
edit: based on posted code
when set mainlist.source
, changes mainlist.view
well. setting list.itemssource
in mainpage
constructor useless (besides, view
property null
@ time anyway). in order fix issue, should move these following lines mainviewmodel
constructor:
this.mainlist.source = app.viewmodel.items; this.mainlist.filter += (s, a) => a.accepted = app.viewmodel.items.indexof((itemviewmodel)a.item) < 10;
that way, set source
once, , view
doesn't change.
Comments
Post a Comment