C# SetValue、GetValue和静态SetPropName()之间的DependencyProperties差异
有两种方法可以访问依赖项属性。行为/反应是否有差异,或者它们的用法是否相似 第一种方法:C# SetValue、GetValue和静态SetPropName()之间的DependencyProperties差异,c#,wpf,dependency-properties,accessor,C#,Wpf,Dependency Properties,Accessor,有两种方法可以访问依赖项属性。行为/反应是否有差异,或者它们的用法是否相似 第一种方法: public static DependencyProperty TestProperty = DependencyProperty.RegisterAttached("Test", typeof (bool), t
public static DependencyProperty TestProperty =
DependencyProperty.RegisterAttached("Test",
typeof (bool),
typeof (MyBaseClass),
new PropertyMetadata(true));
public static bool GetTest(UIElement element)
{
return (bool) element.GetValue(TestProperty);
}
public static void SetTest(UIElement element, bool value)
{
element.SetValue(TestProperty, value);
}
第二种方法:
public static DependencyProperty TestProperty =
DependencyProperty.Register("Test",
typeof (bool),
typeof (MyBaseClass),
new PropertyMetadata(true));
public bool Test {
get {
return (bool) GetValue(TestProperty);
}
set {
SetValue(TestProperty, value);
}
}
这完全取决于您是否能够实际拥有实现此功能的类的实例。实例控件通常用于
CustomControls
和UserControls
。静态类用于Helper/扩展类,其中不可能继承UIElement
,这听起来很清楚。谢谢你的快速回复!后一个属性声明不应使用RegisterAttached,而应使用Register。使用RegisterAttached通过静态getter和setter方法声明附加属性,并使用CLR属性包装器注册常规依赖性属性。有关更多信息,请参阅MSDN上的文章。@Clemens:谢谢你的回答。我更新了这个问题,并改为在第二个方法中注册。这完全取决于,你是否真的可以拥有你正在实现的类的一个实例。实例控件通常用于CustomControls
和UserControls
。静态类用于Helper/扩展类,其中不可能继承UIElement
,这听起来很清楚。谢谢你的快速回复!后一个属性声明不应使用RegisterAttached,而应使用Register。使用RegisterAttached通过静态getter和setter方法声明附加属性,并使用CLR属性包装器注册常规依赖性属性。有关更多信息,请参阅MSDN上的文章。@Clemens:谢谢你的回答。我更新了问题,改为第二种方法注册。