c# - Access local resource to load values to observable collection in codebehind -


i want fill datagrid values of observablecollection property of viewmodel class.

unfortunately following not produce results.

page xaml:

<page.resources>      <vm:vmprojects x:key="projects"/> </page.resources> <grid>     <datagrid x:name="dgprojects" autogeneratecolumns="true"      datacontext="{binding source=projects}" itemssource="{binding projectlist}">         </datagrid>     </grid> </page> 

page code:

vmprojects projects;  public pgprojects() {     initializecomponent();      projects= (vmprojects )this.resources["projects"];     loadlist(projects.projectlist); // database layer, fills collection value (works, there items in collection)  } 

there 2 ways this:

first, since you're creating instance of viewmodel resource, datacontext binding wrong. that's easy , quick fix:

datacontext="{staticresource projects}" 

but since viewmodel seems viewmodel whole page, simplify life more in long run:

<page.datacontext>     <vm:vmprojects /> </page.datacontext>  <grid>     <datagrid          x:name="dgprojects"          autogeneratecolumns="true"         itemssource="{binding projectlist}">         </datagrid> </grid> 

now same instance of vmprojects datacontext entire page, , don't need specify datagrid or other child control.

to in code behind simpler, too:

public pgprojects() {     initializecomponent();      loadlist(viewmodel.projectlist); }  public vmprojects viewmodel => (vmprojects)datacontext; 

Comments