根据我所阅读的内容(我是 SP 新手),ISTM 认为 CreateChildControls() 是向 WebPart 动态添加控件的首选方法,例如:
protected override void CreateChildControls()
{
base.CreateChildControls();
lbl = new Label();
lbl.Text = "Look at this";
this.Controls.Add(lbl);
tb = new TextBox();
this.Controls.Add(tb);
btnSave = new Button();
btnSave.Width = new Unit(50, UnitType.Pixel);
btnSave.Text = "Click me if you dare";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
}
但是,我在这里的遗留代码中看到未使用 CreateChildControls();相反,我看到这样的代码,覆盖 Render():
protected override void Render(HtmlTextWriter output)
{
try
{
List<Announcement> announcements = getAnnouncements(AnnouncementsList);
if (announcements.Count > 0)
output.Write(makeHTML(announcements));
}
catch (Exception e)
{
output.Write("Exception: " + e.Message);
}
}
...然后调用一个自定义方法来让 HTML 呈现:
protected string makeHTML(List<Announcement> announcementList)
{
string r = "<div class='platypus-announcements-panel'>";
r += "<h2 class='platypus-white-panel-title'>" + Header + "</h2>";
r += "<dl>";
foreach (Announcement curr in announcementList)
{
r += "<dt>" + curr.date.ToString("MMM") + "<strong>" + curr.date.Day + "</strong>" + curr.date.ToString("yyyy") + "</dt>";
r += "<dd>" + curr.content + "</dd>";
}
r += "</dl>";
r += "</div>";
return r;
}
以这种方式直接添加 HTML 是否比动态创建控件更可取,如上面 CreateChildControls() 中所示?