ASP.NET中的自定义元素及其子元素

15

我知道在ASP.NET中可以使用用户控件定义自定义标签。但据我所知,您只能向这些控件添加属性。我想要能够嵌入更复杂的数据,有点像这样:

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

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

3个回答

21

这是完全可能的。对于贵方的示例,类应如下所示:

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

谢谢这个.. 对于所有涉及手工构建服务器控件的术语,要得到一个直接的答案真的很困难。回想起来,将内部元素视为属性而不是其他任何东西确实很有道理。干杯! - CResults

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>

0

你不能使用UserControl来实现这样的目的。如上所建议,应该继承Control或WebControl。


1
你为什么发布了相互矛盾的答案? - cchamberlain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接