c# - Object property databinding to a collection item based on a Name of an object -
is possible implement following wpf (silverlight) databinding scenario?
there number of customcontrols on page:
<grid x:name="grid1"> ... <my:custcntr x:name="name1" property1="{binding property1}" /> <my:custcntr x:name="name2" property1="{binding property1}" /> <my:custcntr x:name="name3" property1="{binding property1}" /> ... </grid>
the grid's datacontext
observablecollection:
grid1.datacontext = mycollection; ... observablecollection<myentity> mycollection= new observablecollection<myentity>(); ...
the myentity
class has properties name
, property1
.
myentity me1 = new myentity { name = "name1", property1 = "5" }; myentity me2 = new myentity { name = "name2", property1 = "6" }; myentity me3 = new myentity { name = "name3", property1 = "7" }; ... mycollection.add(me1); mycollection.add(me2); mycollection.add(me3); ...
can establish databinding property1
in each of customcontrols corresponding item of mycollection name
of customcontrol equals value of name
field of collection item?
normally in situation have collection want display on ui use itemscontrol
, listbox
etc. , set itemssource collection. example
<itemscontrol name="itemscontrol1" itemssource="{binding mycollection}"> <itemscontrol.itemspanel> <itemspaneltemplate> <virtualizingstackpanel/> </itemspaneltemplate> </itemscontrol.itemspanel> <itemscontrol.itemtemplate> <datatemplate> <my:custcntr property1="{binding property1}"/> </datatemplate> </itemscontrol.itemtemplate> </itemscontrol>
now datacontext each custcntr
instance of myentity
, binding set between custcntr.property1
, myentity.property1
that said, i'm not sure of reasons current implementation if want create bindings based on name think you'll have resort code behind
xaml
<grid name="grid1" loaded="grid_loaded"> <my:custcntr x:name="name1" /> <my:custcntr x:name="name2" /> <my:custcntr x:name="name3" /> <!--...--> </grid>
code behind
public observablecollection<myentity> mycollection { get; private set; }
update
call method, setbindings, everytime you've modified collection in code. also, use loaded event grid instead set bindings when it's first loaded.
private void grid_loaded(object sender, routedeventargs e) { setbindings(); } private void setbindings() { foreach (uielement element in grid1.children) { if (element custcntr) { custcntr custcntr = element custcntr; foreach (myentity myentity in mycollection) { if (custcntr.name == myentity.name) { binding property1binding = new binding("property1"); property1binding.source = myentity; property1binding.mode = bindingmode.twoway; custcntr.setbinding(custcntr.property1property, property1binding); break; } } } } }
Comments
Post a Comment