C# DependencyProperty保留它';破坏后的价值

C# DependencyProperty保留它';破坏后的价值,c#,.net,wpf,vb.net,dependency-properties,C#,.net,Wpf,Vb.net,Dependency Properties,场景:VB6库通过COM调用.NET程序集中的方法,并使用该方法打开一个WPF对话框,该对话框包含在另一个早期绑定的.NET程序集中。此WPF对话框通过此对话框上ObservableCollection类型的DependencyProperty获得了复杂的主/详细实现。DependencyProperty如下所示: public static readonly DependencyProperty ThatDependencyPropertyProperty = Dependen

场景:VB6库通过COM调用.NET程序集中的方法,并使用该方法打开一个WPF对话框,该对话框包含在另一个早期绑定的.NET程序集中。此WPF对话框通过此对话框上ObservableCollection类型的DependencyProperty获得了复杂的主/详细实现。DependencyProperty如下所示:

public static readonly DependencyProperty ThatDependencyPropertyProperty =
        DependencyProperty.Register("ThatDependencyProperty", typeof(ObservableCollection<SomeClass>)
            , typeof(MainWindow), new UIPropertyMetadata(new ObservableCollection<SomeClass>()));
公共静态只读DependencyProperty ThatDependencyProperty=
DependencyProperty.Register(“ThatDependencyProperty”,类型为(ObservableCollection)
,typeof(主窗口),新的UIPropertyMetadata(新的ObservableCollection());

问题:通过设置DialogResult关闭此对话框并完全重新实例化后,此DependecProperty仍然获得其值,对话框仍然显示以前的主/详细信息。我目前的解决方法是简单地让对话框清除它的ctor中的集合,但我当然不喜欢这样。。。通过两次实例化,什么可以使此集合保持活动状态?

啊,您不应该将
新的ObservableCollection
作为依赖项属性的默认值传入。此单个实例是在静态字段初始值设定项运行时设置的(整个应用程序一次),该集合实例将用作MainWindow每个实例的默认值。您应该只使用值类型或不可变引用类型作为依赖项属性的默认值

相反,您应该将dependency属性的默认值保留为
null
,然后在实例构造函数中,为每个新实例将其设置为
newobserveCollection

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

public MainWindow() {
    this.ThatDependencyProperty = new ObservableCollection<SomeClass>();
}
公共静态只读DependencyProperty ThatDependencyProperty=
DependencyProperty.Register(“ThatDependencyProperty”,类型为(ObservableCollection)
,typeof(主窗口),新UIPropertyMetadata(空);
公共主窗口(){
this.ThatDependencyProperty=新的ObservableCollection();
}