C# Reflection

G

Guest

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.GetProperties();
foreach (PropertyInfo info in propinfo)
{
object val = info.GetValue(temp, 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.
 
D

Daniel Marohn

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()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}

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

}
this.textBox1.Text = sb.ToString();
}

this shows visible=true in the textbox.

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

greets
Daniel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top