如何在ASP.NET Web UserControl中添加自定义内部标签
实现方案
步骤1:定义内部属性对应的实体类
首先创建两个可序列化的属性类,分别对应标签和下拉框的配置项,可按需扩展其他控件属性:
Imports System.ComponentModel Imports System.Web.UI.WebControls <Serializable> Public Class LabelProperty Public Property Text As String Public Property FontBold As Boolean ' 可继续扩展其他Label支持的属性 End Class <Serializable> Public Class DropdownProperty Public Property DataSourceID As String Public Property DataTextField As String Public Property DataValueField As String ' 可继续扩展其他DropDownList支持的属性 End Class
步骤2:在用户控件后台代码中声明内部属性
打开MyControl.ascx.vb文件,添加以下代码声明内部持久化属性,同时实现属性到子控件的赋值逻辑:
Imports System.Web.UI Imports System.ComponentModel Partial Public Class MyControl Inherits System.Web.UI.UserControl ' 声明Label的内部配置属性 <PersistenceMode(PersistenceMode.InnerProperty)> <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> Public Property LabelProperties As New LabelProperty() ' 声明下拉框的内部配置属性 <PersistenceMode(PersistenceMode.InnerProperty)> <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> Public Property DropdownProperties As New DropdownProperty() ' 重写初始化方法,把配置值赋值给实际子控件 Protected Overrides Sub OnInit(e As EventArgs) MyBase.OnInit(e) ' 赋值Label属性 If Not String.IsNullOrEmpty(LabelProperties.Text) Then lbl_Subject.Text = LabelProperties.Text End If lbl_Subject.Font.Bold = LabelProperties.FontBold ' 赋值下拉框属性 If Not String.IsNullOrEmpty(DropdownProperties.DataSourceID) Then ddl_Subject.DataSourceID = DropdownProperties.DataSourceID End If If Not String.IsNullOrEmpty(DropdownProperties.DataTextField) Then ddl_Subject.DataTextField = DropdownProperties.DataTextField End If If Not String.IsNullOrEmpty(DropdownProperties.DataValueField) Then ddl_Subject.DataValueField = DropdownProperties.DataValueField End If End Sub End Class
步骤3:父页面调用方式
和你期望的用法完全一致,直接在控件标签内部添加对应属性标签即可:
<uc:MyControl ID="mc_filter" runat="server"> <LabelProperties Text="Subject" FontBold="true" /> <DropdownProperties DataSourceID="ods_Subject" DataTextField="subject_name" DataValueField="subject_id" /> </uc:MyControl>
注意事项
- 如果需要支持多个同类型子控件的配置,可以把属性定义为List集合类型,配合索引或ID匹配实现对应赋值
- 所有用到的特性都在System.Web.UI和System.ComponentModel官方命名空间下,无需引入第三方组件
内容的提问来源于stack exchange,提问作者Pawich S.
相关产品推荐
相关产品推荐

