Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast elements in UIElementCollection to Type of respective element

In an wpf-Application I want to cast the child elements of a Panel to the respective elements Type.
For example, a UIElementCollection has 3 children:
TextBox
Button
Label

If I iterate the UIElementCollection I’ll get an UIElement and have to cast every element to it’s Type before I can work with it.

So I tried to use a generic method, that will cast the UIElement to it’s real type:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static T getCastTo<T>(UIElement ele)
{                       
     return (T) (object) ele;
              
}

Using it by invoking

TextBox tb = SomeGenerics.getCastTo<TextBox>(ele);

gives me a TextBox as expected.

What I now want to do is using it in a loop something like

foreach(UIElement ele in uielementCollection) {
    SomeGenerics.getCastTo<ele.GetType()>(ele);  // or
    SomeGenerics.getCastTo<typeof(ele)>(ele);
}

but the compiler tells me that I can’t use a variable as a Type.
Is there a way to use the generic method without specifying the Type "manually"?

>Solution :

Just use Enumerable.Cast(hard cast) or Enumerable.OfType(also filters):

IEnumerable<TextBox> allTextBoxes = uielementCollection.OfType<TextBox>();

In general you can’t use a generic methods if you know the type at runtime, generics are a compile time feature. So all you can do is to cast them to the desired type or the common base type. Then you can process them somewhere else by try-casting them to a specifiy type:

foreach (Control c in uielementCollection)
{
    switch (c)
    {
        case TextBox txt:
            // handle TextBox
            break;

        case Label lbl:
            // handle Label
            break;
        //  ... and so on
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading