如何通过指定字符串值来加载UserControl? [英] How can I load a UserControl by specifying a string value?

查看:35
本文介绍了如何通过指定字符串值来加载UserControl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 UserControl ,分别名为a1,a2,b1,b2 ...,我想根据两个变量的值加载其中一个.例如,如果 var1 = a var2 = 1 ,则将加载名为 a1 UserControl .

有没有办法做到这一点?也许还有其他替代方法?

在这里, switch 语句不是可行的选择,因为将有大约200个不同的UserControl.

解决方案

您可以使用.NET Reflection通过其 String 值加载控件.

您可以使用类似这样的代码即时创建对象.

 使用System.Reflection;命名空间WpfApplication1{///< summary>///MainWindow.xaml的交互逻辑///</summary>公共局部类MainWindow:Window{公共MainWindow(){InitializeComponent();//这是UserControl的完整名称空间名称.//您可以使用类似String.Format("WpfApplication1.{0}","uc1")之类的函数来进行传递.字符串ucName ="WpfApplication1.uc1";类型newType = Type.GetType("WpfApplication1.uc1",true,true);对象o = Activator.CreateInstance(newType);//从这里开始使用该对象直到您喜欢的程度.}}} 

I have some UserControls named a1, a2, b1, b2... and I want to load one of them depending of the value of two variables. For example, if var1 = a, var2 = 1, the UserControl named a1 will be loaded.

Is there a way of doing this? Perhaps some other alternate approach?

A switch statement is not a viable option here, because there will be like 200 different UserControls.

解决方案

You can use .NET Reflection to load a control by its String value.

you can use some code like this to create the object on the fly.

using System.Reflection;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //this is the full namespace name of UserControl.
            // you could use something like String.Format("WpfApplication1.{0}", "uc1") to put in a function and pass through.
            string ucName = "WpfApplication1.uc1";

            Type newType = Type.GetType("WpfApplication1.uc1", true, true);

            object o = Activator.CreateInstance(newType);

            //Use the object to how ever you like from here on wards.


        }
    }
}

这篇关于如何通过指定字符串值来加载UserControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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