Harsha
Harsha

Reputation: 113

Setting a value of an attached property via Reflection

I am able to obtain a property called ShowKeyboardCuesProperty which is an attached dependency property present in KeyboardNavigation class. It is an internal static DP with no backing CLR property.

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

I need to set this attached property on another element whose reference I can get easily. Let's refer to that element as DependencyObject d.

How can I call d.SetValue() and set the above attached property(from FieldInfo) to true?

Or is there any other way I can achieve the same?

Upvotes: 1

Views: 664

Answers (1)

mm8
mm8

Reputation: 169270

Try this:

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

Upvotes: 2

Related Questions