Home > database >  Best practice for dependency properties with reference type as default value
Best practice for dependency properties with reference type as default value

Time:01-01

I have the following 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.

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>();
}

CodePudding user response:

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):

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. 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.

  • Related