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

3

我正在阅读关于如何创建参数化样式的教程(此处)。在其中,它使用了一些依赖属性。它将它们声明为:

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来获取值,而另一个不需要?它们在不同的场景下使用吗?


它们除了用法不同外,其余都是相同的。第一种方法使用静态方法,因此可以使用类似于 Control.GetTickBrush([控件实例]) 的语法来设置控件的值。第二种方法通过实例对象让您访问这些值。因此,您需要执行 Control test = new control(); test.MyProperty 来获取或设置该值。 - user2453734
@user2453734:它们不是同一个。请注意,注册它们使用了两种不同的方法。 - O. R. Mapper
很好,一个是用于控件的,它具有类型为“我的属性”的属性(第二个例子)。第二个是可以应用于任何控件的属性。它不是特定于控件的。让我看看是否能找到适当的术语。 - user2453734
http://blogs.msdn.com/b/helloworld/archive/2010/06/25/understanding-wpf-dependency-property-and-attached-property.aspx 是一个很好的例子,可以说明依赖属性和附加依赖属性之间的区别。 - user2453734
1个回答

4
你展示的第一个示例是关于附加属性的,这是一种特殊类型的依赖属性。附加属性的值可以“附加”到其他对象上,而通常的依赖属性属于它们各自类的实例。
第二个代码片段展示了一个普通的依赖属性,如果你只想在创建自定义类时添加额外的依赖属性,那么这是正确的方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接