Frage

Ich bin Erzeugung Usercontrols Zeit wie in einer abstrakten Basisklasse folgt, so dass sie für alle anderen Seiten zur Verfügung, die die Basisklasse implementieren:

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

Was mich an diesem Code nervt ist, dass ich eine Instanz von TopStrapline mit dem LinqToXML schaffen kann, aber es ist nicht gut als Benutzer Kontrolle, weil ich die Usercontrol mit LoadControl müssen laden. Dies funktioniert, aber es scheint ein wenig klobig. Im Idealfall könnte es LoadControl direkt in das pageControls anonyme Objekt auszuführen, und dann die geladene Kontrolle in die Unterkunft Seite zuweisen.

Ist das möglich? Kann jemand empfehlen, eine bessere Lösung für dieses Problem? Dank

War es hilfreich?

Lösung

würde diese Arbeit für Sie?

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

      return control;
  }).FirstOrDefault();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top