代码之家  ›  专栏  ›  技术社区  ›  dnolan

在运行时更改UserControl模板

  •  1
  • dnolan  · 技术社区  · 14 年前

    <ctl:SampleControl runat="server" />
    

    在web.config文件我有

    <controls>
    <add tagPrefix="ctl" tagName="SampleControl" src="~/UserControls/SampleControl.ascx" />
    </controls>
    

    1 回复  |  直到 14 年前
        1
  •  0
  •   Warren Rumak    14 年前

    这里最好的做法是不要对“default.ascx”文件的文件名进行编码web.config文件. 这会让你的生活更艰难。总是在运行时确定,例如:

    在.aspx文件中:

    <asp:PlaceHolder runat="server" ID="samplePH" />
    

    在代码隐藏中:

    string file = "~/UserControls/SampleControl.ascx";
    if (condition)
        file = "~/UserControls/OtherControl.ascx";
    UserControl uc = (UserControl)LoadControl(file);  // from System.Web.UI.TemplateControl.
    samplePH.Controls.Clear();
    samplePH.Controls.Add(uc);
    

    但是,请注意,为了使回发正常工作,您需要在页面生命周期的早期实例化上次请求加载的同一个控件——通常是Init阶段。这将确保正确解析viewstate。然后,在事件处理程序、PreRender等生命周期步骤中,可以使用上面的代码为当前请求加载UserControl。

    如果确实需要在配置文件中对默认页面设置进行编码(对于最终用户可能希望更改它的情况),请考虑在 app.config <controls> a部分web.config文件.

    的文档 TemplateControl.LoadControl(string) 方法: http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.loadcontrol.aspx