目前我在抽象基类中生成如下UserControls,因此它们可用于实现基类的任何其他页面:
// doc is an XML file that may or may not contain a TopStrapline node
var pageControls = new {
TopStrapline = (from strap in doc.Elements("TopStrapline")
select new TopStrapline
{
StraplineText =
(string)strap.Attribute("text")
}).FirstOrDefault(),
// loads of other UserControls generated from other nodes
};
// if there's a StrapLine node, I want to make it available as a property
// in this base class. Any page that needs a TopStrapline can just add the base
// class's TopStrapline to a placeholder on the page.
if (pageControls.TopStrapline != null)
{
this.TopStrapline = GetTopStrapline(pageControls.TopStrapline);
}
private TopStrapline GetTopStrapline(TopStrapline strapline)
{
TopStrapline topStrapline = (TopStrapline)LoadControl("~/Path/TopStrapline.ascx");
topStrapline.StraplineText = strapline.StraplineText;
return topStrapline;
}
我对这段代码感到烦恼的是,我可以使用LinqToXML创建TopStrapline
的实例,但它作为用户控件并不好,因为我需要使用LoadControl
加载UserControl。这有效,但看起来有点笨重。理想情况下,我可以直接在LoadControl
匿名对象中执行pageControls
,然后将该加载的控件分配到页面的属性中。
这可能吗?任何人都可以建议更好地解决这个问题吗?感谢
答案 0 :(得分:1)
这对你有用吗?
this.TopStrapline = doc.Elements("TopStrapline")
.Select(e => {
var control = (TopStrapline)LoadControl("~/Path/TropStrapLine.ascx");
control.StraplineText = e.Attribute("text");
return control;
}).FirstOrDefault();