你是如何声明一个依赖属性?

时间:2013-06-18 19:29:13

标签: c# wpf dependency-properties

我正在阅读有关如何制作参数化样式(here)的教程。在其中,它使用一些依赖属性。它宣称它们是这样的:

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));

现在,我喜欢片段,我继续寻找一个片段,看看我是否不必制作片段。有一个,但风格完全不同:

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));

现在,我没有得到:这两者有什么区别?为什么需要DependencyObject来获取值而另一个不需要?你是在不同的场景中使用它们吗?

1 个答案:

答案 0 :(得分:4)

您展示的第一个示例是attached property,它是一种特殊的依赖属性。附加属性的值可以“附加”到其他对象,而通常的依赖属性属于它们各自类的实例。

第二个代码段显示了一个常规依赖项属性,如果您只想向正在创建的自定义类添加其他依赖项属性,则可以采用这种方式。