Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example of what happens when you use a reference type (collections, etc)
- // as the default value of a dependency property.
- // Not good! Don't do it!
- void Main()
- {
- var bad1 = new BadIdea();
- var bad2 = new BadIdea();
- bad1.Items.Add(1);
- bad1.Items.Add(2);
- bad2.Items.Dump("Bad Instance 2 has data in it's collection, even though I added it via instance 1.");
- var better1 = new BetterIdea();
- var better2 = new BetterIdea();
- better1.Items.Add(1);
- better1.Items.Add(2);
- better2.Items.Dump("Better Instance 2 works as expected. No Items in collection.");
- }
- // Don't do it this way...
- class BadIdea : DependencyObject
- {
- public ObservableCollection<int> Items
- {
- get { return (ObservableCollection<int>)GetValue(ItemsProperty); }
- set { SetValue(ItemsProperty, value); }
- }
- public static readonly DependencyProperty ItemsProperty =
- DependencyProperty.Register(
- "Items",
- typeof(ObservableCollection<int>),
- typeof(BadIdea),
- new UIPropertyMetadata(new ObservableCollection<int>())
- );
- }
- // Do it this way... with the constructor
- class BetterIdea : DependencyObject
- {
- public BetterIdea()
- {
- Items = new ObservableCollection<int>();
- }
- public ObservableCollection<int> Items
- {
- get { return (ObservableCollection<int>)GetValue(ItemsProperty); }
- set { SetValue(ItemsProperty, value); }
- }
- public static readonly DependencyProperty ItemsProperty =
- DependencyProperty.Register(
- "Items",
- typeof(ObservableCollection<int>),
- typeof(BetterIdea),
- new UIPropertyMetadata(null)
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement