动态呈现控件,确定从字符串/ XML文件类型? [英] Dynamically rendering controls, determine type from string/XML File?

查看:101
本文介绍了动态呈现控件,确定从字符串/ XML文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET应用程序中,我想动态呈现几个控件及其属性从XML文档来英寸这就是它与众不同:我希望能够动态地确定控制的类型。所以,我的XML文档中,我有这样的事情:

In an ASP.NET application, I'd like to dynamically render several controls with their properties coming in from an XML document. Here's the kicker: I want to be able to dynamically determine the type of control. So, in my XML document, I have something like this:

    <control>
    <id>myControl1</id>
    <type>CheckBox</type>
    <text>Text For This Control</text>
    </control>

我能得到的一切工作正常,至于性能去,只要我手动实例化新的控制为复选框...但我似乎无法弄清楚如何使一个复选框,与一文本框或任何基于XML的信息...

I can get everything to work fine, as far as properties go, so long as I manually instantiate the new control as a checkbox...but I can't seem to figure out how to make it a checkbox, versus a textbox or whatever based on the XML information...

推荐答案

您可能希望能够控制无法控制的类型的输出。我的建议是:

You will probably want to be able to control the output beyond the type of Control. My suggestion:

public interface IControlProvider {
    public Control GetControl(XmlElement controlXml);
};

public class ControlProviderFactory : IControlProvider {
    private Dictionary<string,IControlProvider> providers = new Dictionary<string,IControlProvider>();

    public ControlProviderFactory() {
        //Add concrete implementations of IControlProvider for each type
    }

    public Control GetControl(XmlElement controlXml) {
        string type = (controlXml.SelectSingleNode("type") as XmlElement).InnerText;
        if(!providers.ContainsKey(type) throw new Exception("No provider exists for " + type);
        return providers[type].GetControl(controlXml);
    }
}

您还可以添加一个ReflectionControlProvider作为非注册的类型后备,让这种使用Activator.CreateInstance,而不是遇到一个未知的供应商类型时抛出异常。这样,你得到渲染和动态创建的两个特定控制的最大灵活性。

You could also add a ReflectionControlProvider as a fallback for non registered types and let this use Activator.CreateInstance instead of throwing an Exception when encountering an unknown provider type. This way you get maximum flexibility for both specific control of rendering and dynamic creation.

这篇关于动态呈现控件,确定从字符串/ XML文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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