是否可以将UserControl加载到匿名对象中,而不仅仅是实例化它? [英] Is it possible to load a UserControl into an anonymous object, instead of just instantiating it?

查看:91
本文介绍了是否可以将UserControl加载到匿名对象中,而不仅仅是实例化它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我在抽象基类中生成UserControl,如下所示,因此它们可用于实现该基类的任何其他页面:

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;
}

令我烦恼的是,我可以使用LinqToXML创建TopStrapline的实例,但是作为用户控件并不合适,因为我需要用LoadControl加载UserControl.这行得通,但似乎有点笨拙.理想情况下,我可以直接在pageControls匿名对象中执行LoadControl,然后将该加载的控件分配给页面的属性.

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

推荐答案

这对您有用吗?

this.TopStrapline = doc.Elements("TopStrapline")
  .Select(e => {
      var control = (TopStrapline)LoadControl("~/Path/TropStrapLine.ascx");
      control.StraplineText = e.Attribute("text");

      return control;
  }).FirstOrDefault();

这篇关于是否可以将UserControl加载到匿名对象中,而不仅仅是实例化它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆