c# - WPF TreeView does not pick up templates, calls ToString() instead -
this question has answer here:
i have in xaml:
<treeview datacontext="{binding source={staticresource locator}}" itemssource="{binding sometree.toplevelitems}"> <treeview.resources> <datatemplate datatype="{x:type vm:ileaf}"> <checkbox content="{binding name}" isthreestate="false" ischecked="{binding isenabled, mode=twoway, updatesourcetrigger=propertychanged}" /> </datatemplate> <hierarchicaldatatemplate datatype="{x:type vm:igroup}" itemssource="{binding children}"> <checkbox content="{binding name}" isthreestate="true" ischecked="{binding isenabled, mode=twoway, updatesourcetrigger=propertychanged}" /> </hierarchicaldatatemplate> </treeview.resources> </treeview>
vm:
defined accordingly:
xmlns:vm="clr-namespace:my.viewmodels.mytree"
and mytree
namespace contains interfacesigroup
, ileaf
.
the sometree.toplevelitems
enumerable of igroup
s , ileaf
s (it populated dynamically).
now, treeview should display tree of checkboxes accordingly, displaying top-level elements of items source, not applying data template, , calls tostring()
on elements instead.
the other post mentions same problem not apply here, checked that.
what missing / doing wrong?
templates work off concrete classes not interfaces,
this feature if have 2 interfaces on 1 class template should select?
as system can't know not allowed it
see full ms response here https://social.msdn.microsoft.com/forums/vstudio/en-us/1e774a24-0deb-4acd-a719-32abd847041d/data-templates-and-interfaces?forum=wpf
instead use datatemplateselector rather type up, way can tell system how interpret multi interface situation
public class tasklistdatatemplateselector : datatemplateselector { public override datatemplate selecttemplate(object item, dependencyobject container) { frameworkelement element = container frameworkelement; if (element != null && item != null && item task) { task taskitem = item task; if (taskitem.priority == 1) return element.findresource("importanttasktemplate") datatemplate; else return element.findresource("mytasktemplate") datatemplate; } return null; } }
Comments
Post a Comment