是否可以将 UserControl 加载到匿名对象中,而不仅仅是实例化它?
目前,我正在抽象基类中生成如下 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;
}
这段代码让我烦恼的是,我可以使用以下命令创建 TopStrapline
的实例: LinqToXML,但它作为用户控件并不好,因为我需要使用 LoadControl
加载 UserControl。这可行,但看起来有点笨拙。理想情况下,我可以直接在 pageControls
匿名对象中执行 LoadControl
,然后将加载的控件分配给页面的属性。
这可能吗?谁能提出一个更好的解决方案来解决这个问题?谢谢
Currently I'm generating UserControls as follows in an abstract base class so they are available for any other pages that implement the base class:
// 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;
}
What's bugging me about this code is that I can create an instance of TopStrapline
with the LinqToXML but it's no good as a user control because I need to load the UserControl with LoadControl
. This works but it seems a bit clunky. Ideally I could execute LoadControl
directly into the pageControls
anonymous object, and then assign that loaded control into the page's property.
Is this possible? Can anyone suggest a better solution to this issue? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对你有用吗?
Would this work for you?