Custom elements in ASP.NET with custom child-elements

折月煮酒 提交于 2019-12-02 17:41:41

It is certainly possible. For your example the classes would look like:

[ParseChildren(true)]
class MyGraph : WebControl {
    List<Color> _colors = new List<Color>();
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public List<Color> Colors {
        get { return _colors; }
    }
}

class Color {
    public string Value { get; set; }
}

And the actual markup would be:

<myControls:MyGraph id="myGraph1" runat="server">
   <Colors>
     <myControls:Color Value="#abcdef" />
     <myControls:Color Value="#123456" />
   </Colors>
</myControls:MyGraph>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace ComponentDemo
{
    [ParseChildren( true )]
    public class MyGraph : System.Web.UI.WebControls.WebControl
    {
        private List<Color> _colors;

        public MyGraph() : base() { ;}

        [PersistenceMode( PersistenceMode.InnerProperty )]
        public List<Color> Colors
        {
            get 
            {
                if ( null == this._colors ) { this._colors = new List<Color>(); }
                return _colors; 
            }
        }
    }

    public class Color
    {
        public Color() : base() { ;}
        public string Value { get; set; }
    }
}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ComponentDemo._Default" %>
<%@ Register Assembly="ComponentDemo" Namespace="ComponentDemo" TagPrefix="my" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <my:MyGraph runat="server">
            <Colors>
                <my:Color Value="value1" />
                <my:Color Value="value2" />
                <my:Color Value="value3" />
                <my:Color Value="value4" />
            </Colors>
        </my:MyGraph>
    </div>
    </form>
</body>
</html>

You cannot user UserControl for such purpoces. As adviced above, inherit Control or WebControl.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!