Reputation: 22814
I was reading a tutorial on how to make a parametrized style (here). In it, it uses some dependency properties. It declares them as such:
public static Brush GetTickBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(TickBrushProperty);
}
public static void SetTickBrush(DependencyObject obj, Brush value)
{
obj.SetValue(TickBrushProperty, value);
}
public static readonly DependencyProperty TickBrushProperty =
DependencyProperty.RegisterAttached(
"TickBrush",
typeof(Brush),
typeof(ThemeProperties),
new FrameworkPropertyMetadata(Brushes.Black));
Now, as I like snippets, I went ahead and looked for one, to see if I didn't have to make one. There was one, but in a completely different style:
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));
Now, what I don't get: what's the difference between these two? Why does one need a DependencyObject
to get the value while the other one doesn't? Do you use them in separate scenarios?
Upvotes: 3
Views: 459
Reputation: 20760
The first example you show is for an attached property, which is a special kind of a dependency property. Values of attached properties can be "attached" to other objects, while usual dependency properties belong to the instances of their respective class.
The second code snippet shows a regular dependency property and is the way to go if you just want to add an additional dependency property to a custom class you are creating.
Upvotes: 4