开发者

Is it possible to load a UserControl into an anonymous object, instead of just instantiating it?

开发者 https://www.devze.com 2023-01-03 04:53 出处:网络
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:

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 =
                                              开发者_StackOverflow社区(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


Would this work for you?

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

      return control;
  }).FirstOrDefault();
0

精彩评论

暂无评论...
验证码 换一张
取 消