【问题标题】:Setting a value of an attached property via Reflection通过反射设置附加属性的值
【发布时间】:2017-02-07 16:13:04
【问题描述】:

我能够获得一个名为 ShowKeyboardCuesProperty 的属性,它是 KeyboardNavigation 类中存在的附加依赖属性。它是一个没有支持 CLR 属性的内部静态 DP。

(typeof(KeyboardNavigation).GetMember("ShowKeyboardCuesProperty", MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)[0] as FieldInfo)

我需要在另一个元素上设置这个附加属性,我可以很容易地得到它的引用。让我们将该元素称为 DependencyObject d。

如何调用 d.SetValue() 并将上述附加属性(来自 FieldInfo)设置为 true?

或者有没有其他方法可以达到同样的效果?

【问题讨论】:

  • 附加属性严格来说是 XAML 的一项功能。这与 Windows API 编程无关。

标签: c# wpf xaml reflection dependency-properties


【解决方案1】:

试试这个:

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

【讨论】:

  • 感谢您的指导。
猜你喜欢
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2020-05-18
  • 1970-01-01
相关资源
最近更新 更多