控件標籤內容可解析為屬性值(如 TextBox.Text)或子控件集合(如 Panel.Controls),透過 ParseChildrenAttribute 與 ControlBuilderAttribute 精確控制解析行為。
| 建構式 | 行為 |
|---|---|
ParseChildrenAttribute() | ChildrenAsProperties=false,內容不解析為屬性 |
ParseChildrenAttribute(bool) | 指定是否解析為屬性 |
ParseChildrenAttribute(Type) | 內容解析為指定型別的子控件 |
ParseChildrenAttribute(bool, string) | 指定 ChildrenAsProperties 與預設屬性名(DefaultProperty) |
Control 基類預設 ChildrenAsProperties=false(解析為子控件)WebControl 標記 [ParseChildren(true, "Text")],預設解析為 Text 屬性| 枚舉值 | 序列化形式 | 適用場景 |
|---|---|---|
| Attribute | 標籤屬性 Property="value" | 簡單型別 |
| EncodedInnerDefaultProperty | 內部文字(HTML 編碼),唯一預設屬性 | 字串屬性(如 ListItem.Text) |
| InnerDefaultProperty | 內部文字(不編碼),唯一預設屬性 | 允許 HTML 內容 |
| InnerProperty | 巢狀標籤 <Property>...</Property> | 複雜物件、集合(如 DropDownList.Items) |
[ParseChildren(true, "Items")]
[DefaultProperty("Items")]
public class DropDownList : WebControl
{
[PersistenceMode(PersistenceMode.InnerProperty)]
public ListItemCollection Items { get; }
}
public class ListItem
{
[PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty)]
public string Text { get; set; }
}
解析:Items 為集合屬性用 InnerProperty(巢狀標籤),ListItem.Text 為字串用 EncodedInnerDefaultProperty(內部文字自動編碼)。
protected override void AddParsedSubObject(object obj)
{
if (obj is LiteralControl literal)
Text = literal.Text; // 純文字內容存入 Text 屬性
else
throw new ArgumentException("僅允許靜態文字內容");
}
缺點:每次請求都執行,效率較低。
[ControlBuilder(typeof(MyControlBuilder))]
public class MyControl : Control { }
public class MyControlBuilder : ControlBuilder
{
public override bool AllowWhitespaceLiterals() => false; // 去除首尾空白
public override bool HtmlDecodeLiterals() => true; // 移除 HTML 編碼
}
優點:僅在頁面編譯/解析階段執行一次,效能最佳。
WebControl 且需自訂解析:標記 [ParseChildren(false)] + [ControlBuilder(...)][ParseChildren(true, "PropertyName")] + [PersistenceMode(EncodedInnerDefaultProperty)]InnerProperty + 子類別標記對應屬性