views:

25

answers:

1

Scenario: A VB6 library calls a method in a .NET-Assembly through COM and with that opens a WPF-Dialog, which is contained in another .NET-Assembly that is early bound. This WPF-Dialog got a complex master/detail implementation over a DependencyProperty of type ObservableCollection on this dialog. The DependencyProperty looks something like this:

public static readonly DependencyProperty ThatDependencyPropertyProperty =
        DependencyProperty.Register("ThatDependencyProperty", typeof(ObservableCollection<SomeClass>)
            , typeof(MainWindow), new UIPropertyMetadata(new ObservableCollection<SomeClass>()));

Problem: After this dialog gets closed through setting DialogResult and is being completely re-instantiated, this DependecyProperty still got it's values and the dialog is still displaying the previous master/detail information. My current workaround is to simply let the dialog clear the collection in it's ctor, but I certainly don't like this... what could keep this collection alive through two instantiations?

+1  A: 

Ahh you should not pass new ObservableCollection in as the default value for your dependency property. This single instance is set up when the static field initializers run (one time for the whole application) and that collection instance will be used as the default value for every instance of MainWindow. You should only use value types or immutable reference types as a default value for a dependency property.

Instead you should leave the default value for the dependency property as null and then in your instance constructor, set it to a new ObservableCollection for each new instance.

public static readonly DependencyProperty ThatDependencyPropertyProperty =
    DependencyProperty.Register("ThatDependencyProperty", typeof(ObservableCollection<SomeClass>)
        , typeof(MainWindow), new UIPropertyMetadata(null));

public MainWindow() {
    this.ThatDependencyProperty = new ObservableCollection<SomeClass>();
}
Josh Einstein
Thank you, I'll try that.
naacal