هل من الممكن تحميل UserControl في كائن مجهول ، بدلاً من مجرد إنشاء مثيل له؟

StackOverflow https://stackoverflow.com/questions/3015390

سؤال

حاليًا أقوم بإنشاء 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 ولكنه ليس جيدًا كعنصر تحكم للمستخدم لأنني بحاجة إلى تحميل USERCONTROL LoadControl. هذا يعمل ولكن يبدو قليلا clunky. من الناحية المثالية يمكنني التنفيذ LoadControl مباشرة في pageControls كائن مجهول ، ثم تعيين عنصر تحكم تم تحميله في خاصية الصفحة.

هل هذا ممكن؟ هل يمكن لأي شخص اقتراح حل أفضل لهذه القضية؟ شكرًا

هل كانت مفيدة؟

المحلول

هل سيعمل هذا من أجلك؟

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

      return control;
  }).FirstOrDefault();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top