c# - Dependency property in custom control is sharing memory/values unexpectedly -
i have following set up:
- custom wpf control (base class), deriving
canvas
- implementation of base class
- an
observablecollection<t>
dependency property on implementation
i have test app displays 3 unique instances of custom control (e.g. <custom:mycontrol x:name="test1" />
, test2, test3, , on). when run , debug app, contents of observablecollection<t>
same 3 instances of control. why this?
chart:
[contentproperty("datagroups")] public abstract class chart : canvas { static chart() { defaultstylekeyproperty.overridemetadata(typeof(chart), new frameworkpropertymetadata(typeof(chart))); } public observablecollection<chartdata> datagroups { { return (observablecollection<chartdata>)getvalue(datagroupsproperty); } set { setvalue(datagroupsproperty, value); } } public static readonly dependencyproperty datagroupsproperty = dependencyproperty.register("datagroups", typeof(observablecollection<chartdata>), typeof(chart), new frameworkpropertymetadata(new observablecollection<chartdata>(), frameworkpropertymetadataoptions.affectsarrange)); public abstract void refresh(); }
chartdata:
[contentproperty("points")] public class chartdata : frameworkelement { public observablecollection<point> points { { return (observablecollection<point>)getvalue(pointsproperty); } set { setvalue(pointsproperty, value); } } public static readonly dependencyproperty pointsproperty = dependencyproperty.register("points", typeof(observablecollection<point>), typeof(chartdata), new propertymetadata(new observablecollection<point>())); }
one way modify chart data (assuming multiple data groups), example:
mychart.datagroups[index].points.add(new point() { y = somenumber }); mychart.refresh();
but every instance inside datagroups[]
identical.
the same thing happening if define collection(s) via xaml, so:
<c:chart x:name="charta"> <c:chartdata x:name="datagroup1" /> <c:chartdata x:name="datagroup2" /> </c:chart>
then, in code, access defined collections:
charta.datagroups[0].points.add(new point() { y = somenumber }); charta.refresh();
you havent done wrong. design. shall work way. set value in constructor instead , not have singleton.
http://msdn.microsoft.com/en-us/library/aa970563.aspx
initializing collection beyond default value
when create dependency property, not specify property default value initial field value. instead, specify default value through dependency property metadata. if property reference type, default value specified in dependency property metadata not default value per instance; instead default value applies instances of type. therefore must careful not use singular static collection defined collection property metadata working default value newly created instances of type. instead, must make sure deliberately set collection value unique (instance) collection part of class constructor logic. otherwise have created unintentional singleton class.
Comments
Post a Comment