With dependency properties being so heavily used across the WPF platform, there is a good chance that sooner or later you will get bitten by this issue my colleague Hristo Deshev and I were debugging not long ago. Some heads-up can't really hurt anybody so here it is;).

We will declare a simple class Foo with a single collection dependency property (note that this is a reference type). We will also supply our brand new property with a default value through the convenient DependecyProperty.Register(...) method:


Let us put our class to the test by creating two Foo instances and adding a single item to each Bars collection property:


Works as simple as that! But... I got a strange feeling about this -- let's run the debugger on the same piece of code just to make sure everything is OK.

The first Foo instance contains a single item in its Bar collection as expected:



However, the Bars content of the second instance might not be what one would expect:


As the excellent debugging utility "Make Object ID" tips us, it seems all distinct Foo object instances share the same Bars collection object -- thus when you add an item to a single Foo.Bars collection, you are essentially adding the item to the Bars collection of all Foo objects.

Most probably you are not trying to utilize this static feature of the WPF dependency properties so you can eliminate it by moving the default value declaration from the DependencyProperty.Register(...) call to the Foo constructor:


And here is the debugger once again (Make Object ID also states this is a separate object now {#2}):




Related Posts


Comments are disabled in preview mode.