.net 如何创建只读依赖属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1122595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do You Create a Read-Only Dependency Property?
提问by Giffyguy
How do you create a read-only dependancy property? What are the best-practices for doing so?
如何创建只读依赖属性?这样做的最佳做法是什么?
Specifically, what's stumping me the most is the fact that there's no implementation of
具体来说,最让我难受的是没有实施
DependencyObject.GetValue()
that takes a System.Windows.DependencyPropertyKeyas a parameter.
将 aSystem.Windows.DependencyPropertyKey作为参数。
System.Windows.DependencyProperty.RegisterReadOnlyreturns a DependencyPropertyKeyobject rather than a DependencyProperty. So how are you supposed to access your read-only dependency property if you can't make any calls to GetValue? Or are you supposed to somehow convert the DependencyPropertyKeyinto a plain old DependencyPropertyobject?
System.Windows.DependencyProperty.RegisterReadOnly返回一个 DependencyPropertyKey对象而不是 a DependencyProperty。那么,如果您无法调用 GetValue,您应该如何访问您的只读依赖项属性?或者你应该以某种方式将它转换DependencyPropertyKey成一个普通的旧DependencyProperty对象?
Advice and/or code would be GREATLY appreciated!
建议和/或代码将不胜感激!
回答by Kenan E. K.
It's easy, actually (via RegisterReadOnly):
实际上很简单(通过RegisterReadOnly):
public class OwnerClass : DependencyObject // or DependencyObject inheritor
{
private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey
= DependencyProperty.RegisterReadOnly(
nameof(ReadOnlyProp),
typeof(int), typeof(OwnerClass),
new FrameworkPropertyMetadata(default(int),
FrameworkPropertyMetadataOptions.None));
public static readonly DependencyProperty ReadOnlyPropProperty
= ReadOnlyPropPropertyKey.DependencyProperty;
public int ReadOnlyProp
{
get { return (int)GetValue(ReadOnlyPropProperty); }
protected set { SetValue(ReadOnlyPropPropertyKey, value); }
}
//your other code here ...
}
You use the key only when you set the value in private/protected/internal code. Due to the protected ReadOnlyPropsetter, this is transparent to you.
仅当您在私有/受保护/内部代码中设置值时才使用该密钥。由于受保护的ReadOnlyPropsetter,这对您来说是透明的。

