c# - WPF binding ObservableCollection with converter -
i have observablecollection of strings , i'm tring bind converter listbox , show strings start prefix.
wrote:
public observablecollection<string> names { get; set; } public mainwindow() { initializecomponent(); names= new observablecollection<names>(); datacontext = this; }
and converter:
class nameslistconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, system.globalization.cultureinfo culture) { if (value == null) return null; return (value icollection<string>).where((x) => x.startswith("a")); } public object convertback(object value, type targettype, object parameter, system.globalization.cultureinfo culture) { return null; } }
and xaml:
<listbox x:name="fileslist" itemssource="{binding path=names, converter={staticresource nameslistconverter}}" />
but listbox not update after beed update (add or remove).
have notice if removes converter binding works perfectly. wrong code?
your converter creating new collection objects in original observablecollection. itemssource set using binding no longer original observablecollection. understand better, equal have wrote:
public object convert(object value, type targettype, object parameter, system.globalization.cultureinfo culture) { if (value == null) return null; var list = (value icollection<string>).where((x) => x.startswith("a")).tolist(); return list; }
the list converter returning new object copy of data source collection. further changes in original collection not reflected in new list listbox not know changes. if want filter data take collectionviewsource.
edit: how filter
public observablecollection<string> names { get; set; } public icollectionview view { get; set; } public mainwindow() { initializecomponent(); names= new observablecollection<string>(); var viewsource = new collectionviewsource(); viewsource.source=names; //get icollectionview , set filter view = viewsource.view; //filter predicat, items start "a" view.filter = o => o.tostring().startswith("a"); datacontext=this; }
in xaml set itemssource collectionview
<listbox x:name="fileslist" itemssource="{binding path=view}"/>
Comments
Post a Comment