C#Winform的动态加载用户控件的名字 [英] C# Winform dynamically load usercontrols by name

查看:218
本文介绍了C#Winform的动态加载用户控件的名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能动态加载用户控件?
这是一些code来说明我的意思:

I want to know if it's possible to dynamically load user controls?
This is some code to show what I mean:

public void Load()
        {

            Reset();

            if (_host.User == null)
                return;

            int _count = 0;

            String[] _applications = _host.User.Applications;

            if (_applications == null)
                return;

            foreach (String _application in _applications)
            {

                TabPage _page = null;

                switch (_application)
                {
                    case "SF01":

                        _page = new TabPage();
                        _page.Text = "SF01";
                        _page.Controls.Add(new SF01(_container));

                        break;
                }

                if (_page != null)
                {

                    tapplications.TabPages.Add(_page);
                    m_list.Add(_count, _page);
                    _count++;

                }

            }

            tapplications.TabPages.Add(tlog);

            if (_host.User.Admin)
                tapplications.TabPages.Add(tadmin);

            _container.Controls.Add(this);

        }

正如你可以看到 SF01 是我的用户。
现在我该怎样去加载其他用户控件 按名称而不是硬键入类对象?
这样我可以创造更多的应用程序,而忘记了如何加载它们。 (案SF01:)的
所有的应用程序都将驻留在项目文件夹应用程序之下,也许有一种方法可以遍历该项目文件夹?

As you can see SF01 is my usercontrol.
Now how do I go about loading other usercontrols by name instead of hard typing the class object?
This way I can create more applications and forget about how to load them. (case "SF01":)

All the applications will reside beneath a project folder applications, maybe there is a way to iterate through that project folder?

推荐答案

是的,它是。

一个用户控制可使用的 Activator.CreateInstance ,任何其他类型的对象。

A User Control can be instanciated using Activator.CreateInstance, as any other kind of object.

string objTypeName = "myNamespace.UI.SF01"; // Full namespace name
SF01 myNewSF01 = (Foo)Activator.CreateInstance(Type.GetType(objTypeName));

然后你可以替换你的switch语句

Then you can replace your switch statement with

_page = new TabPage();
_page.Text = "SF01";

var control = (Control)Activator.CreateInstance(Type.GetType("myNamespace." + _application));
_page.Controls.Add(control);

这篇关于C#Winform的动态加载用户控件的名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆