且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义控件中的依赖项属性意外共享内存/值

更新时间:2022-12-13 08:41:49

您没有做错任何事情。这是设计使然。它应该以这种方式工作。只需在构造函数中设置您的值,就不会出现单例。

You havent done anything wrong. It is by design. It shall work that way. Just set your value in constructor instead and you will not have a singleton.

http://msdn.microsoft.com/en-us/library/aa970563.aspx

初始化超出默认值的集合值

Initializing the Collection Beyond the Default Value

创建依赖项属性时,请勿将属性默认值指定为初始字段值。相反,您可以通过依赖项属性元数据指定默认值。如果您的属性是引用类型,则在依赖项属性元数据中指定的默认值不是每个实例的默认值;相反,它是适用于该类型的所有实例的默认值。因此,必须小心不要将collection属性元数据定义的单个静态collection用作类型的新创建实例的工作默认值。相反,您必须确保在类构造函数逻辑中故意将集合值设置为唯一(实例)集合。否则,您将创建一个意外的单例类。

When you create a dependency property, you do not specify the property default value as the initial field value. Instead, you specify the default value through the dependency property metadata. If your property is a reference type, the default value specified in dependency property metadata is not a default value per instance; instead it is a default value that applies to all instances of the type. Therefore you must be careful to not use the singular static collection defined by the collection property metadata as the working default value for newly created instances of your type. Instead, you must make sure that you deliberately set the collection value to a unique (instance) collection as part of your class constructor logic. Otherwise you will have created an unintentional singleton class.