C# (WPF) Casting UIElement into an Type of class without knowing the type

18 Views Asked by At

I would like to cast an UIElement to a Type of class the generic way, because I don't know what kinds of UIElements are given.

Example: I have some UserControls, let's say UC1 and UC2. Now I have a method that have to check a property from these controls. The propery is a dependecy property so UIElement doesn't know about it.

I know, I can do easily like that:

var _uc1prop = ((UC1)my_ui_element).MyProperty;
var _uc2prop = ((UC2)my_ui_element).MyPoperty;

That's easy to build in a switch/case, but I'm searching for a solution where I don't have to know what kind of Type the object is from.

Something like this ( I know that this doesn't work! )

Type t = my_ui_element.GetType();
var _ucprop = my_ui_element.Cast<t>().MyProperty;

or

var _ucprop = (my_ui_element as t).MyProperty

The reason I'm searching for something like this is that in future I could have some new UserControls that have to be processed by the method and I don't want to expand the method any time.

I hope it's understandable, othwerwise let me know.

Thanks

0

There are 0 best solutions below