我希望创建一个用以下内容创建的用户/服务器控件:
<my:MyListControl runat="server"> <asp:ListItem Text="Test1" Value="Test1" /> <asp:ListItem Text="Test2" Value="Test2" /> </my:MyListControl>
我应该从哪个基类继承?要覆盖什么?
可能如何自定义我的控件接受的子项(my:ListItem而不是asp:ListItem).
我想要做的是为我网站的一小部分创建一个非常简单的面包屑控制.我使用库存ASP.NET控件,但这些项目都添加在代码中,这意味着修复拼写错误或格式化错误涉及重新编译,这是不理想的.
编辑:
命名空间MySite.Controls
部分类BreadCrumbs
继承UserControl
Private m_BreadCrumbs As New List(Of BreadCrumbItem) <PersistenceMode(PersistenceMode.InnerProperty)> _ Public Property Items() As List(Of BreadCrumbItem) Get Return m_BreadCrumbs End Get Set(ByVal value As List(Of BreadCrumbItem)) m_BreadCrumbs = value End Set End Property Private Sub Page_Load(ByVal sender As Object,ByVal e As EventArgs) Handles MyBase.Load Bind() End Sub Private Sub Bind() lvCrumbs.DataSource = Items Me.DataBind() End Sub End Class Public Class BreadCrumbItem Private m_Text As String Public Property Text() As String Get Return m_Text End Get Set(ByVal value As String) m_Text = value End Set End Property Private m_Url As String Public Property Url() As String Get Return m_Url End Get Set(ByVal value As String) m_Url = value End Set End Property End Class
结束命名空间
<%@ Page Language="VB" AutoEventWireup="false" Inherits="MySite.MyPage" Title="My Page" Codebehind="MyPage.aspx.vb" %> <%@ Register TagPrefix="my" Namespace="MySite.Controls" Assembly="MySite" %> <my:BreadCrumbs ID="breadcrumbs" runat="server"> <Items> <my:BreadCrumbItem Text="Another page" Url="AnotherPage.aspx" /> </Items> </my:BreadCrumbs>
解决方法
您可以在用户控件的代码后面添加属性,如:
[PersistenceMode(PersistenceMode.InnerProperty)] public List<ListItem> Items { get; set; }
您的标记将是:
<my:MyListControl runat="server"> <Items> <asp:ListItem/> </Items> </my:myListControl>
为了使它成为可能,ListItem可以是你自己的列表项(我推荐这样做而不是使用asp.net.)你需要创建自己的类.
这是我使用的服务器控件的一个例子(我删除了很多噪音,因为这只是一个骨架):
[ToolBoxData("<{0}:Menubar runat=server></{0}:Menubar>")] [System.ComponentModel.DesignTimeVisible(false)] public class Menubar : WebControl,IPostBackEventHandler { private List<MenuItem> _menuItems = new List<MenuItem>(); [PersistenceMode(PersistenceMode.InnerProperty)] public List<MenuItem> MenuItems { get { return _menuItems; } } } [ToolBoxItem(false)] [ParseChildren(true,"MenuItems")] public class MenuItem { private string _clientClick; private List<MenuItem> _menuItems = new List<MenuItem>(); [Localizable(true)] public string Title { get; set; } public string Href { get; set; } public string Id { get; set; } [PersistenceMode(PersistenceMode.InnerDefaultProperty)] public List<MenuItem> MenuItems { get { return _menuItems; } set { _menuItems = value; } } }
现在我可以这样使用:
<my:Menubar runat="server" ID="menuBar"> <MenuItems> <my:MenuItem Title="Save" Href="javascript:saveItem(this);" /> <my:MenuItem Title="Print" Href="javascript:void(0);"> <MenuItems> <my:MenuItem Title="Preview" Href=""/> <my:MenuItem Title="To Pdf" Href="javascript:"/> </MenuItems> </my:MenuItem> </MenuItems> </my:Menubar>