C# Reflection

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?VGltIFBhY2w=?=

    #1

    C# Reflection

    I am new to Reflection. I am building a windows app that navigates the
    control tree of a Windows form and creates XAML representing the form. I am
    using reflection to get the properties of each control to create the
    XmlAttributes for the Control's XAML node. The problem is, regardless of how
    I set the 'Visible' property for a control in the form, its value is always
    read as "False" through reflection.

    Here is a snippet of my code:
    Type temptype = temp.GetType();
    PropertyInfo[] propinfo = temptype.GetPro perties();
    foreach (PropertyInfo info in propinfo)
    {
    object val = info.GetValue(t emp, null);
    ....
    }

    where temp is the source form Control.

    When info is "Visible", val = "False". This is always the case even when I
    specifically set the controls Visible property to True.

    Is this a bug with C#? Or is my inexperience with Reflection coming through?

    Your help is appreciated.
  • Daniel Marohn

    #2
    Re: C# Reflection

    Hi Tim,
    When info is "Visible", val = "False". This is always the case even when I
    specifically set the controls Visible property to True.
    Your code works, but I thing you use it in a situation when the form,
    containing the control was not build complete (perhaps in the construcor?).

    See this example:

    a simple form, with one button and one textbox:
    public Form1()
    {
    InitializeCompo nent();
    this.Load += new EventHandler(Fo rm1_Load);
    }

    void Form1_Load(obje ct sender, EventArgs e)
    {
    Control temp = this.button1;
    Type temptype = temp.GetType();
    PropertyInfo[] propinfo = temptype.GetPro perties();
    System.Text.Str ingBuilder sb = new System.Text.Str ingBuilder();
    foreach (PropertyInfo info in propinfo)
    {
    object val = info.GetValue(t emp, null);
    if (!(val == null))
    {
    sb.AppendLine( info.Name + ": " + val.ToString()) ;
    }
    else
    {
    sb.AppendLine( info.Name + ": " + "null");
    }

    }
    this.textBox1.T ext = sb.ToString();
    }

    this shows visible=true in the textbox.

    Now delete the line 'this.load += new EventHandler(Fo rm1_Load);'
    and call 'this.Form1_Loa d(this, EventArgs.Empty );' directly in the
    constructor.
    As you can see, the visible property is false now.

    greets
    Daniel


    Comment

    Working...