我必須有某種語法錯誤。出於某種原因,我的依賴對象表現得像靜態一樣。我沿着以下線的東西:如何防止DependencyObjects在所有實例之間共享其DependencyProperties?
public void main()
{
MyClass C1 = new MyClass();
MyClass C2 = new MyClass();
C1.StringCollection.Add("Test1");
Console.WriteLine(C2.StringCollection.First());
}
public class MyClass : DependencyObject
{
public static DependencyProperty StringCollectionProperty = DependencyProperty.Register(
"StringCollection",
typeof(ObservableCollection<string>),
typeof(MyClass),
new PropertyMetadata(new ObservableCollection<string>()));
public ObservableCollection<string> StringCollection
{
get { return(ObservableCollection<string>)GetValue(StringCollectionProperty); }
set { SetValue(StringCollectionProperty, value); }
}
}
給出了下面的輸出:
Test1
元素加入到C2將在C1的StringCollection,反之亦然。任何想法我做錯了什麼?
'DependencyProperty'將保持每個對象的值,但它共享其默認值,在您的情況下'ObservableCollection'。如果它是一個引用類型,它將是相同的值。初始化爲null –
dkozl
2014-09-29 09:58:00