[英]Child Controls of custom control not rendering correctly
我要添加幾個控件作為我開發的另一個自定義控件的子控件。 這是我添加子控件(自定義標簽和通用跨度控件)的地方:
public static void AddLabel(this IExtendedControl control, string inheritableCssClass = "")
{
TestCLabel contentLabel = new TestCLabel();
contentLabel.Text = control.LabelText;
control.Controls.Add(contentLabel);
if (control.Required)
{
HtmlGenericControl requiredFieldIndicator = new HtmlGenericControl("span");
requiredFieldIndicator.Attributes["class"] = "requiredFieldIndicator";
requiredFieldIndicator.InnerText = " *";
control.Controls.Add(requiredFieldIndicator);
}
然后在父控件的render方法中執行以下操作:
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
foreach (Control c in this.Controls)
{
c.RenderControl(w);
}
if (Required)
{
rfv.RenderControl(w);
}
}
但出現錯誤“具有相同密鑰的條目已存在”。 這是由於嘗試手動呈現子控件引起的。 我認為我不需要進行手動渲染,但是在我在控件中編碼之前沒有出現(HTML標記中沒有任何內容)。 有什么想法嗎?
看起來手動控制子控件並不是問題。 我對代碼進行了重新設計,因為我最初是將子控件分配給父控件的屬性,但是更改了此代碼以將子控件添加到父控件的控件集合中(這樣子控件現在就可以通過其正確的生命周期了) )。 我以前一直在將子控件作為父控件的屬性時手動呈現它們,並且仍在這樣做。 手動渲染所有子項時,將第二次添加控件。 仍然沒有回答:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.