zoukankan      html  css  js  c++  java
  • 为Asp.Net的用户控件添加类似DropDownList的下拉属性

    在上一章中我们讲解了如何在用户控件中添加简单属性与枚举属性,链接如下:
    在Asp.net中为用户控件(.ascx)添加自定义属性详解

    这一章我们讲解如何为Asp.Net的用户控件添加类似DropDownList的下拉属性,如下图所示:


    从图片中可以看到,WebUserControl1控件是一个用户控件,但它却可以像DropDownList控件一样,在aspx源码中设置下拉集合项。这是怎么实现的呢?

    为了节省时间,我们就不像上一章说的那么详细了。

    首先我们新建一个WebUserControl1.ascx用户控件,为了简单,我们就直接在该控件中放一个DropDownList控件。如果我们不为WebUserControl1.ascx控件添加任何属性,在该控件外是不能够为DropDownList控件添加下拉项的。

    现在我们为WebUserControl1.ascx控件添加一个Items属性,它直接映射DropDownList的Items属性,属性如下:

    public ListItemCollection Items
    {
        get { return this.DropDownList1.Items; }
    }

    这样,我们在调用该用户控件的aspx页的cs文件中,就可以通过编程的方式为DropDownList控件添加下拉项了,如下:

    protected void Page_Load(object sender, EventArgs e)
    {
        this.WebUserControl11.Items.Add(new ListItem("中国银行", "0"));
    }

    但这时我还无法在aspx直接为DropDownList控件添加下拉项的。

    现在我们为用户控件的Items属性添加一个属性,如下代码:

    [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
    public ListItemCollection Items
    {
        get { return this.DropDownList1.Items; }
    }

    讲解一下上面代码的意思:
    PersistenceMode:定义元数据属性 (Attribute),用于指定如何在设计时将 ASP.NET 服务器控件属性 (Property) 或事件保存到 ASP.NET页
    PersistenceMode.InnerDefaultProperty:指定属性在 ASP.NET 服务器控件中保持为内部文本。还指示将该属性定义为元素的默认属性。只能指定一个属性为默认属性

    仅仅设置了这个属性,还是不够的,我们还需要为用户控件类添加一个属性:

    [ParseChildren(true, "Items")]
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
    }

    ParseChildren:定义可在开发 ASP.NET 服务器控件时使用的元数据属性。使用 System.Web.UI.ParseChildrenAttribute 类指示页分析器应如何处理页上声明的服务器控件标记中嵌套的内容。

    好了,设置完这两步,重新编译用户控件,然后再重新打开调用该用户控件的页面,是不是可以在aspx页面直接设置下拉集合项了呢 :)

    示例控件的全部源码如下:
    ascx:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"
        Inherits="WebApplication1.WebUserControl1" % >
    <asp:DropDownList ID="DropDownList1" runat="server" >
    </asp:DropDownList >

    ascx.cs:

    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebApplication1
    {
        [ParseChildren(true, "Items")]
        public partial class WebUserControl1 : System.Web.UI.UserControl
        {
            [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
            public ListItemCollection Items
            {
                get { return this.DropDownList1.Items; }
            }

            protected void Page_Load(object sender, EventArgs e)
            {

            }
        }
    }

  • 相关阅读:
    插件集合
    postgis_LayerTransform
    react-高阶组件
    react-自定义事件
    Immutable 详解及 React 中实践
    babel-preset-env: a preset that configures Babel for you
    彻底解决Webpack打包慢的问题
    打包图片
    drag
    brush
  • 原文地址:https://www.cnblogs.com/wyfs/p/2400373.html
Copyright © 2011-2022 走看看