这似乎很奇怪,但我将一些自定义的WPF用户控件投射到WPF UserControl,我必须调用一些包含所有这些方法的方法。可能吗?怎么做?如何调用某些WPF用户控件的“隐藏”方法
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.
注:方法Hide()
是公开的。
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();
}
}
哪里是
public void Hide()
{
// do stuff
}
谢谢!你的解决方案非常优雅!埃尔诺岩石! –
不客气。请注意,我更喜欢解决方案来实现这个接口。只有当我不得不使用反射时,我才考虑这个“动态”解决方案,因为我无法访问UserControl。 –