Timo Korinth

2 Meter, 2 Mark

Dependency property of type collection

| 0 comments

Today I get trapped by a common problem:

For a custom control I’ve created a dependency property of type ObservableCollection<object>, that should accept any UI element. The code looked like this:

[AlternateContentProperty, Category("Common Properties")]
public ObservableCollection<object> CharmButtons
{
    get { return (ObservableCollection<object>)GetValue(CharmButtonsProperty); }
    set { SetValue(CharmButtonsProperty, value); }
}

public static readonly DependencyProperty CharmButtonsProperty =
    DependencyProperty.Register("CharmButtons", typeof(ObservableCollection<object>), typeof(ExtContentControl),
    new UIPropertyMetadata(new ObservableCollection<object>()));

The project has compiled and there were no problems at run-time. However, I have used multiple instances of my custom control in several views, and even if I had not set the dependency property, the same content occurs.

The problem is the initialization of the default value ​​in the metadata. For simple value types (such as string or int), the static initialization will cause no problem, because the values ​​are overwritten in the instances of the control. However, if a static collection, as in this example, is initialized and only been set by an individual control, there is only one instance of this collection (as a singleton) set. This leads to the effect, that all controls are sharing the same content.

To solve this problem, you have to set the dependency property’s default value to null and initialize it in the empty constructor:

public ExtContentControl()
{
    this.CharmButtons = new ObservableCollection<object>();
}

[AlternateContentProperty, Category("Common Properties")]
public ObservableCollection<object> CharmButtons
{
    get { return (ObservableCollection<object>)GetValue(CharmButtonsProperty); }
    set { SetValue(CharmButtonsProperty, value); }
}

public static readonly DependencyProperty CharmButtonsProperty =
    DependencyProperty.Register("CharmButtons", typeof(ObservableCollection<object>), typeof(ExtContentControl),
    null);

Leave a Reply