通过反射设置附加 属性 的值
Setting a value of an attached property via Reflection
我能够获得一个名为 ShowKeyboardCuesProperty 的 属性,它是 KeyboardNavigation class 中存在的附加依赖项 属性。它是一个内部静态 DP,没有支持 CLR 属性。
(typeof(KeyboardNavigation).GetMember("ShowKeyboardCuesProperty", MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)[0] as FieldInfo)
我需要将此附加 属性 设置在另一个我可以轻松获取其引用的元素上。让我们将该元素称为 DependencyObject d.
如何调用 d.SetValue() 并将上面附加的 属性(来自 FieldInfo)设置为 true?
或者有没有其他方法可以达到同样的效果?
试试这个:
FieldInfo fi = (typeof(KeyboardNavigation).GetMember("ShowKeyboardCuesProperty",
MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)[0] as FieldInfo);
DependencyObject o = new Button();
DependencyProperty dp = fi.GetValue(o) as DependencyProperty;
bool value = (bool)o.GetValue(dp); //= false
o.SetValue(dp, true);
value = (bool)o.GetValue(dp); // = true
我能够获得一个名为 ShowKeyboardCuesProperty 的 属性,它是 KeyboardNavigation class 中存在的附加依赖项 属性。它是一个内部静态 DP,没有支持 CLR 属性。
(typeof(KeyboardNavigation).GetMember("ShowKeyboardCuesProperty", MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)[0] as FieldInfo)
我需要将此附加 属性 设置在另一个我可以轻松获取其引用的元素上。让我们将该元素称为 DependencyObject d.
如何调用 d.SetValue() 并将上面附加的 属性(来自 FieldInfo)设置为 true?
或者有没有其他方法可以达到同样的效果?
试试这个:
FieldInfo fi = (typeof(KeyboardNavigation).GetMember("ShowKeyboardCuesProperty",
MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)[0] as FieldInfo);
DependencyObject o = new Button();
DependencyProperty dp = fi.GetValue(o) as DependencyProperty;
bool value = (bool)o.GetValue(dp); //= false
o.SetValue(dp, true);
value = (bool)o.GetValue(dp); // = true