【问题标题】:Is it possible to load a UserControl into an anonymous object, instead of just instantiating it?是否可以将 UserControl 加载到匿名对象中,而不仅仅是实例化它?
【发布时间】:2010-06-10 14:33:38
【问题描述】:

目前,我正在抽象基类中生成如下 UserControl,以便它们可用于实现该基类的任何其他页面:

// 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 匿名对象中,然后将该加载的控件分配给页面的属性。

这可能吗?任何人都可以提出更好的解决方案来解决这个问题吗?谢谢

【问题讨论】:

    标签: c# asp.net user-controls linq-to-xml anonymous-objects


    【解决方案1】:

    这对你有用吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 2011-04-08
      相关资源
      最近更新 更多