Advertisement
nathanaw

Reference type instances for defaults in Dependency Property

Sep 8th, 2011
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. // Example of what happens when you use a reference type (collections, etc)
  2. // as the default value of a dependency property.
  3. // Not good! Don't do it!
  4. void Main()
  5. {
  6.     var bad1 = new BadIdea();
  7.     var bad2 = new BadIdea();
  8.     bad1.Items.Add(1);
  9.     bad1.Items.Add(2);
  10.     bad2.Items.Dump("Bad Instance 2 has data in it's collection, even though I added it via instance 1.");
  11.  
  12.     var better1 = new BetterIdea();
  13.     var better2 = new BetterIdea();
  14.     better1.Items.Add(1);
  15.     better1.Items.Add(2);
  16.     better2.Items.Dump("Better Instance 2 works as expected. No Items in collection.");
  17. }
  18.  
  19. // Don't do it this way...
  20. class BadIdea : DependencyObject
  21. {
  22.     public ObservableCollection<int> Items
  23.     {
  24.         get { return (ObservableCollection<int>)GetValue(ItemsProperty); }
  25.         set { SetValue(ItemsProperty, value); }
  26.     }
  27.    
  28.     public static readonly DependencyProperty ItemsProperty =
  29.         DependencyProperty.Register(
  30.             "Items",
  31.             typeof(ObservableCollection<int>),
  32.             typeof(BadIdea),
  33.             new UIPropertyMetadata(new ObservableCollection<int>())
  34.         );
  35. }
  36.  
  37. // Do it this way... with the constructor
  38. class BetterIdea : DependencyObject
  39. {
  40.  
  41.     public BetterIdea()
  42.     {
  43.         Items = new ObservableCollection<int>();
  44.     }
  45.    
  46.     public ObservableCollection<int> Items
  47.     {
  48.         get { return (ObservableCollection<int>)GetValue(ItemsProperty); }
  49.         set { SetValue(ItemsProperty, value); }
  50.     }
  51.    
  52.     public static readonly DependencyProperty ItemsProperty =
  53.         DependencyProperty.Register(
  54.             "Items",
  55.             typeof(ObservableCollection<int>),
  56.             typeof(BetterIdea),
  57.             new UIPropertyMetadata(null)
  58.         );
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement