It seems strange but I cast some custom WPF User Controls to WPF UserControl and I have to call some method which have all of them. Is it possible? How to do it?
foreach (var kid in ((MainWindow)App.Current.Windows[0]).MainCanvas.Children)
{
string kidType = kid.GetType().FullName;
if (kidType.EndsWith("MyUserControl"))
{
UserControl myUserControl = (UserControl)kid;
myUserControl.Hide() // <- this method I want to call bu it is "hidden" because of teh casting which doesn't provide access to it.
Note: The method Hide() is public.
SOLUTION:
Hi all!
Thanks for your input! Finally I got the solution.
foreach (var kid in ((MainWindow)App.Current.Windows[0]).MainCanvas.Children)
{
string kidType = kid.GetType().FullName;
if (kidType.EndsWith("UControl"))
{
Type t = kid.GetType();
object obj = Activator.CreateInstance(t);
t.InvokeMember("Hide", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, new object[] { });
// And here there is a 1000% better solution of @Erno
// dynamic myUserControl = kid;
// myUserControl.Hide();
}
}
where is
public void Hide()
{
// do stuff
}
dynamicmight be useful to prevent writing reflection code (See this):Make sure you add some exception handling just in case you encounter a type that fits the name but doesn’t implement Hide.
If you are worried about that you could implement an interface on all the UserControls and try-cast to that interface instead.