在没有页面的情况下使用LoadControl

Bru*_*oLM 8 c# asp.net

如何在没有Page的情况下加载控件?

public void Something()
{
    var ascx = /*LoadControl*/("my.ascx"); // being Page = null
    var ctl1 = ascx.Controls[0];
    var ctl2 = ascx.Controls[1];
}
Run Code Online (Sandbox Code Playgroud)

my.ascx:

<%@ Control Language="C#" %>
<asp:Literal ID="ctl1" runat="server" />
<asp:Label ID="ctl2" runat="server" />
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 14

您可以通过以下方式从HttpContext获取Page-Object:

Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
     // Use page instance to load your Usercontrol
}
Run Code Online (Sandbox Code Playgroud)