c# - defining bindings for elements in a collection in xaml wont work -
i have simple control collection of elements. want add elements in xaml , bind element.
however when bind bar.value in xaml never works. minimal example:
[contentproperty("bars")] public class foocontrol : control { private observablecollection<ibar> _bars = new observablecollection<ibar>(); public observablecollection<ibar> bars { { return _bars; } } } public interface ibar { string value { get; } } public class bar : dependencyobject, ibar { public static readonly dependencyproperty valueproperty = dependencyproperty.register("value", typeof(string), typeof(bar), new propertymetadata("<not set>")); public string value { { return (string)getvalue(valueproperty); } set { setvalue(valueproperty, value); } } }
<window x:class="wpftestapplication.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:this="clr-namespace:wpftestapplication" xmlns:sys="clr-namespace:system;assembly=mscorlib" title="mainwindow" height="200" width="1000"> <window.resources> <style targettype="this:foocontrol"> <setter property="template"> <setter.value> <controltemplate targettype="this:foocontrol"> <itemscontrol itemssource="{binding bars, relativesource={relativesource templatedparent}}"> <itemscontrol.itemtemplate> <datatemplate> <textblock text="{binding value}"/> </datatemplate> </itemscontrol.itemtemplate> </itemscontrol> </controltemplate> </setter.value> </setter> </style> </window.resources> <window.datacontext> <sys:string>from datacontext</sys:string> </window.datacontext> <grid> <this:foocontrol> <this:bar value="directly set"/> <this:bar value="{binding source=from_binding_source}"/> <this:bar value="{binding}"/> <this:bar value="{binding text, elementname=sometextblock}"/> </this:foocontrol> <textblock text="from textbox" name="sometextblock" visibility="collapsed"/> </grid> </window>
output
directly set from_binding_source "<not set>" "<not set>"
debug output
system.windows.data error: 2 : cannot find governing frameworkelement or frameworkcontentelement target element. bindingexpression:path=text; dataitem=null; target element 'bar' (hashcode=26568931); target property 'value' (type 'string')
any suggestion how work?
my current workaround define bindings in code lot more code , looking @ xaml not obvious bindings exists. (see answer workaround code)
dont know if helps but
[contentproperty("bars")] public class foocontrol : control { private observablecollection<object> _bars = new observablecollection<object>(); public observablecollection<object> bars { { return _bars; } } }
xaml
<this:foocontrol> <this:bar value="directly set"/> <this:bar value="{binding source=from_binding_source}"/> <textblock text="{binding}"/> <textblock text="{binding text, elementname=sometextblock}"/> </this:foocontrol>
you desired result
Comments
Post a Comment