priyanka.sarkar
priyanka.sarkar

Reputation: 26498

Determine WPF element type

How to determine the element type in WPF programatically?

For example my xaml is consisting of textbox, radio buttons, combo's, list boxes etc.

In the load event, say I want to do something related to the controls.(Say for all textbox,

the foreground color will be red, for all labels the background color will be green)..

something of that sort.

So I have to loop through the entire list of controls present in the Xaml and then have to

write the control specific logic.

Is it by using Framework element?

Please give the code in c#. For example please take 3/4 controls of your choice.

I am also searching in google!

Thanks in advance

Upvotes: 2

Views: 11454

Answers (3)

benPearce
benPearce

Reputation: 38333

if you only have a finite number of types to check against try casting using the "as" operator and then checking for null.

Button button = control as Button;
if (button != null)
{
  // this is a button)
}
...

The as operator will not throw an exception if the cast cannot be done.


EDIT: IF you are only trying to achieve styling of the controls you should look at the <Style/> tag.

See here for a good example

Upvotes: 5

Konstantin
Konstantin

Reputation:

You can use:

if (element is Grid)
{
}
else if (element is Label)
...

Upvotes: 10

Gishu
Gishu

Reputation: 136613

GetType() should work if you have a reference to the control/type.

Upvotes: 3

Related Questions