ASP.NET中的自定义元素,带有自定义子元素

时间:2009-03-23 13:22:56

标签: asp.net custom-controls

我知道可以使用用户控件在ASP.NET中定义自定义标记。但据我所知,您只能为这些控件添加属性。我希望能够嵌入更复杂的数据,有点精简:

<myControls:MyGraph id="myGraph1" runat="server">
   <colors>
     <color>#abcdef</color>
     <color>#123456</color>
   </colors>
</myControls:MyGraph>

这可能在ASP.NET中实现吗?我应该尝试扩展ListView吗?还是有更好更正确的解决方案?

3 个答案:

答案 0 :(得分:19)

当然可以。对于您的示例,类看起来像:

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

实际的标记是:

<myControls:MyGraph id="myGraph1" runat="server">
   <Colors>
     <myControls:Color Value="#abcdef" />
     <myControls:Color Value="#123456" />
   </Colors>
</myControls:MyGraph>

答案 1 :(得分:4)

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>

答案 2 :(得分:0)

您无法为此类purpoc用户使用UserControl。如上所述,继承Control或WebControl。