c# - WPF - ObservableCollection<object> DP -


i intend create pager control restrict observablecollection (with kinds of types) defined amount. therefore, created usercontrol following dp:

public static readonly dependencyproperty itemsourceproperty = dependencyproperty.register("itemsource", typeof(observablecollection<object>), typeof(pagercontrol),new propertymetadata(null, itemsourcechanged));  private static void itemsourcechanged(dependencyobject sender, dependencypropertychangedeventargs e) {     pagecontrol pagecontrol = (pagecontrol)sender;     pagecontrolviewmodel viewmodel = ((pagecontrolviewmodel)pagecontrol.datacontext;     viewmodel.setitemsource(e.newvalue); }  public observablecollection<object> itemsource {     => (cast..)getvalue(itemsourceproperty);     set => setvalue(itemsourceproperty, value); } 

my idea is, after itemsource has been changed, viewmodel receives new collection , able register following event

public void setitemsource(observablecollection<object> itemsource) {     this.itemsource = itemsource;     this.itemsource.collectionchanged += dostuff; } 

dostuff like: itemsource.skip().take() , binds other observablecollection, whichever can used datagrids.

so far good, encounter following problem. itemsourcechanged gets called (as bind it) , itemsource dp has instance , not defined default value null. has instance. if bind pagercontrol's itemsource observablecollection values, itemsourcechanged has no entries @ , in addition, not same object 1 bound to. therefore, collectionchanged never called when original observablecollection receives new entries.

pagercontrol usage in xaml

<datagrid itemsource={binding elementname=pager, path=restricteditemsource} /> <pager x:name="pager" itemsource={binding collection} /> 

the xaml viewmodel

public observablecollection<class> collection { get; set; } = new ...();  public viewmodel() {     collection.add(x);     collection.add(y);     collection.add(z); } 

note: code snippets top of head.

after 3 days of searching , stackoverflow post, found mistake. pagecontrol had own viewmodel (datacontext) , therefore, binding in mainwindow.xaml (or whichever control included pagecontrol) not bind itemsource correctly, because pagecontrol's datacontext own one.

it working flawlessly following change

<datagrid itemsource={binding elementname=pager, path=restricteditemsource} /> <pager x:name="pager" itemsource={binding path=datacontext.collection, relativesource={relativesource mode=find, ancestortype=usercontrol}}" /> 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -