[英]Best practice for dependency properties with reference type as default value
I have the following DependencyProperty:我有以下 DependencyProperty:
public static DependencyProperty ItemsProperty = DependencyProperty.Register(nameof(Items), typeof(ObservableCollection<ContentControl>), typeof(Group), new PropertyMetadata(new ObservableCollection<ContentControl>()));
Now as you can see giving it a reference type as a default value will only work once, as soon as i create a second instance of this class they will share that reference.现在你可以看到给它一个引用类型作为默认值只会工作一次,只要我创建这个 class 的第二个实例,他们就会共享该引用。
I could not find much about it and what the best way would be, anyone has a suggestion?我找不到太多关于它的信息,最好的方法是什么,有人有建议吗?
One way to do it would be to not give it a default value and set the reference with a new instance in the constructor:一种方法是不给它默认值并在构造函数中使用新实例设置引用:
public static DependencyProperty ItemsProperty = DependencyProperty.Register(nameof(Items), typeof(ObservableCollection<ContentControl>), typeof(Group));
public Group()
{
Items = new ObservableCollection<ContentControl>();
}
The way you have figured out is the best practice as far as I am aware.据我所知,您找到的方法是最佳实践。
To quote from Microsoft's article Collection-type dependency properties (WPF .NET) :引用微软的文章Collection-type dependency properties (WPF .NET) :
When you create a dependency property, you typically specify the default value through dependency property metadata instead of specifying an initial property value.创建依赖属性时,通常通过依赖属性元数据指定默认值,而不是指定初始属性值。 However, if your property value is a reference type, the default value should be set in the constructor of the class that registers the dependency property.但是,如果你的属性值是引用类型,默认值应该在注册依赖属性的class的构造函数中设置。 The dependency property metadata shouldn't include a default reference-type value because that value will be assigned to all instances of the class, creating a singleton class.依赖属性元数据不应包含默认引用类型值,因为该值将分配给 class 的所有实例,从而创建 singleton class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.