是否有可能一个用户控件加载到一个匿名对象,而不是仅仅将其实例化?
-
26-09-2019 - |
题
目前我生成用户控件作为一个抽象基类,所以它们可用于实现该基类的任何其他页面如下:
// 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
加载用户控件。这工作,但似乎有点笨重。理想的情况下,我可以执行LoadControl
直接进入pageControls
匿名对象,然后分配该加载的控制到页面的属性。
这是可能的?任何人都可以提出一个更好的解决这个问题?感谢
解决方案
这会为你工作?
this.TopStrapline = doc.Elements("TopStrapline")
.Select(e => {
var control = (TopStrapline)LoadControl("~/Path/TropStrapLine.ascx");
control.StraplineText = e.Attribute("text");
return control;
}).FirstOrDefault();
不隶属于 StackOverflow