简体   繁体   中英

Dynamically rendering controls, determine type from string/XML File?

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>

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);
    }
}

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.

您可以创建有效类型的Dictionary<string, Type> ,也可以使用Activator.CreateInstance通过名称创建实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM