wpf 只读依赖项属性
示例
何时使用
只读的依赖项属性与普通的依赖项属性相似,但其结构不允许从控件外部设置其值。如果您拥有仅供消费者参考的属性,则此方法很好用,例如IsMouseOver或IsKeyboardFocusWithin。
如何定义
与标准依赖项属性一样,只读依赖项属性必须在从派生的类上定义DependencyObject。
public class MyControl : Control
{
private static readonly DependencyPropertyKey MyPropertyPropertyKey =
DependencyProperty.RegisterReadOnly("MyProperty", typeof(int), typeof(MyControl),
new FrameworkPropertyMetadata(0));
public static readonly DependencyProperty MyPropertyProperty = MyPropertyPropertyKey.DependencyProperty;
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
private set { SetValue(MyPropertyPropertyKey, value); }
}
}适用于常规依赖项属性的约定也适用于此处,但有两个主要区别:
在DependencyProperty从源privateDependencyPropertyKey。
在CLR的属性设置是protected或private不是public。
需要注意的是二传手传递MyPropertyPropertyKey,而不是MyPropertyProperty到SetValue方法。由于该属性是只读定义的,因此任何尝试SetValue对该属性使用的尝试都必须与具有receive的重载一起使用DependencyPropertyKey。否则,InvalidOperationException将抛出。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短