自訂控制項產生器範例
下列範例將定義一個自訂控制項產生器 (NoWhiteSpaceControlBuilder
) 並將它和自訂控制項 (NoWhiteSpaceControl
) 關聯。為比較起見,同時也加入一個不包含自訂產生器的第二個控制項。若要建置這個範例,請參閱伺服器控制項範例中的說明。
namespace CustomControls
{
using System;
using System.Web.UI;
public class NoWhiteSpaceControlBuilder : ControlBuilder
{
public override bool AllowWhitespaceLiterals()
{
return false;
}
}
[ ControlBuilderAttribute(typeof(NoWhiteSpaceControlBuilder))]
public class NoWhiteSpaceControl : Control
{}
public class WhiteSpaceControl : Control
{}
}
[Visual Basic]
Option Explicit
Option Strict
Imports System
Imports System.Web.UI
Namespace CustomControls
Public Class NoWhiteSpaceControlBuilder
Inherits ControlBuilder
Public Overrides Function AllowWhitespaceLiterals() As Boolean
Return False
End Function
End Class
<ControlBuilderAttribute(GetType(NoWhiteSpaceControlBuilder))> _
Public Class NoWhiteSpaceControl
Inherits Control
End Class
Public Class WhiteSpaceControl
Inherits Control
End Class
End Namespace
自訂控制項產生器範例測試網頁
下列 .aspx 網頁將使用一個擁有自訂控制項產生器的自訂控制項 NoWhiteSpaceControl
。為比較起見,網頁中也包含一個使用預設控制項產生器的控制項 (WhiteSpaceControl
)。
<%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %>
<html>
<body>
<form runat=server>
<pre>
<Custom:NoWhiteSpaceControl Id = "NoSpace" runat=server>
This control does not allow white spaces.
<asp:Label runat = server id = "nospacel1" Text = "First label inside no white space control." />
<asp:Label runat = server id = "nospacel2" Text = "Second label after white space ." />
</Custom:NoWhiteSpaceControl>
<br><br>
<Custom:WhiteSpaceControl Id = "Space" runat=server>
This control allows white spaces.
<asp:Label runat = server id = "spacel1" Text = "First label inside white space control." />
<asp:Label runat = server id = "spacel2" Text = "Second label after white space." />
</Custom:WhiteSpaceControl>
</pre>
</form>
</body>
</html>
請參閱
控制項產生器概觀 | ControlBuilderAttribute | 控制項剖析、ParseChildrenAttribute 和控制項產生器