C#Winform的动态加载用户控件的名字控件、加载、名字、动态

2023-09-06 11:38:00 作者:你丑没事我嗐

我想知道是否有可能动态加载用户控件? 这是一些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);