Custom elements in ASP.NET with custom child-elements

后端 未结 3 599
我寻月下人不归
我寻月下人不归 2021-01-31 11:53

I know that it is possible to define custom tags in ASP.NET with User Controls. But as far as I know you can only add attributes to these controls. I would like to be able to em

相关标签:
3条回答
  • 2021-01-31 12:12

    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>
    
    0 讨论(0)
  • 2021-01-31 12:12
    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 讨论(0)
  • 2021-01-31 12:21

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

    0 讨论(0)
提交回复
热议问题