如何更改继承的依赖项属性的默认值?在我们的例子中,我们创建了一个Control的子类,默认情况下它的Focusable设置为'true'.我们希望我们的子类具有默认值'false'.
我们一直在做的只是在构造函数中将其设置为'false',但如果有人使用ClearValue,它将返回默认值,而不是构造函数中设置的值.
以下是我目前正在做的事情(这是一个带有'Foo'DP的测试控件的例子.)我不是隐藏属性的'新'的粉丝虽然感谢AddOwner,但它确实指出了到同一个共享实例所以我猜它没关系.它看起来像是继承了所有其他元数据值,所以这很好.只是想知道这是否正确?
public class TestControlBase : Control
{
public static readonly DependencyProperty FooProperty = DependencyProperty.Register(
"Foo",
typeof(int),
typeof(TestControlBase),
new FrameworkPropertyMetadata(4) // Original default value
);
public int Foo
{
get { return (int)GetValue(FooProperty); }
set { SetValue(FooProperty, value); }
}
}
public class TestControl : TestControlBase
{
public static readonly new DependencyProperty FooProperty = TestControlBase.FooProperty.AddOwner(
typeof(TestControl),
new FrameworkPropertyMetadata(67) // New default for this subclass
);
}
Run Code Online (Sandbox Code Playgroud)
标记
更新中...
我认为这更好,因为它消除了"新"呼叫.您仍然可以通过基类上的FooProperty访问它,因为它使用了AddOwner.因此,它在技术上是相同的.
public class TestControl : …Run Code Online (Sandbox Code Playgroud) 我正在尝试将一个PropertyChangedCallback添加到UIElement.RenderTransformOriginProperty.当我尝试覆盖PropertyMetadata时抛出异常.
我搜索过MSDN和谷歌,我能想到的就是这个.在该帖子的某些时候建议使用DependencyPropertyDescriptor.AddValueChanged,但这不会解决我的问题,因为这不是每个实例的回调.
我不明白这个例外意味着什么.有谁知道我做错了什么?
public class foo : FrameworkElement
{
private static void Origin_Changed( DependencyObject d,
DependencyPropertyChangedEventArgs e)
{ }
static foo()
{
PropertyMetadata OriginalMetaData =
UIElement.RenderTransformOriginProperty.GetMetadata(
typeof(FrameworkElement));
/*An exception is thrown when this line is executed:
"Cannot change property metadata after it has been associated with a property"*/
OriginalMetaData.PropertyChangedCallback +=
new PropertyChangedCallback(Origin_Changed);
UIElement.RenderTransformOriginProperty.OverrideMetadata(
typeof(foo), OriginalMetaData);
}
}
Run Code Online (Sandbox Code Playgroud) .net c# dependency-properties exception invalidoperationexception