retrieve the instance of a class from the information contained in a MemberInfo in C# WPF

66 Views Asked by At

After many fruitless searches I can't find the solution.

I want to do something like this Object obj = memberInfo.GetInstance();

Here is the method:

        public static void DefineControl(Window currentForm, Role role)
        {
            foreach (MemberInfo member in currentForm.GetType().GetMembers())
            {
                Attribute ? attribute = member.GetCustomAttribute<AccessCategory>();
                if (attribute != null)
                {
                    bool authorized = ((AccessCategory)attribute).Authorized(role.Categories.ToArray());
                    if (!authorized)
                    {

                        Type type = currentForm.GetType();
                        FieldInfo field = type.GetField(member.Name);
                        Control control = (Control)field.GetValue(member); // control is null <- problem here
                        control.IsEnabled = false;
                    }
                }
            }
        }

I can't get the instance of member

Thank you for your help!

A.

1

There are 1 best solutions below

6
On

As it's a property, you will have to use PropertyInfo instead of FieldInfo

A rough solution..

internal class Program
{
    static void Main(string[] args)
    {
        Button button1 = new Button();
        Type t = button1.GetType();

        var MemberInfo = t.GetMembers();
        foreach (var member in MemberInfo)
        {
            if (member.Name == "IsEnable")
            {
                //set IsEnable Property to true
                ((PropertyInfo)member).SetValue(button1, true);
            }
        }

        //temp.Configure();
    }
}
class Button
{
    public bool IsEnable { get; set; }
}