c# - Getting null item in select template of DataTemplateSelector -
i trying use contenttemplateselector of contentcontrol load datatemplate in code behind.
for first time alone, getting null in argument item of selecttemplate.
here code snippet.
public mainwindow() { initializecomponent(); this.datacontext = new orderinforepositiory(); contentcontrol c1 = new contentcontrol(); c1.contenttemplateselector = new edittemplateselector(); c1.setbinding(contentcontrol.contentproperty, new binding()); this.addchild(c1); } public class celltemplateselector : datatemplateselector { public override datatemplate selecttemplate(object item, dependencyobject container) { return base.selecttemplate(item, container); } }
let me have reason behind that.
thanks.
to understand reason behind behavior describe have analyze code.
the contentcontrol
c1 not belong visual tree until call addchild method, there no need "disturb" contenttemplateselector
. instead when add c1 window, contenttemplateselector decide template control should apply.
addind c1 window means changing datacontext too. control asks contenttemplateselector new datatemplate. when happens selecttemplate
method called, parameter "item" null, since binding (you created line: c1.setbinding(contentcontrol.contentproperty, new binding());) not aware source (i mean datacontext) changed yet.
after datacontext changed event processed, binding begins work , modifies c1's contentproperty. the selecttemplate method called , time item parameter not null.
if not behavior, either declare contentcontrol
in xaml or add window immedialty after create it:
contentcontrol c1 = new contentcontrol(); this.addchild(c1); c1.contenttemplateselector = new templateselector(); c1.setbinding(contentcontrol.contentproperty, new binding());
i hope can you.
Comments
Post a Comment