.net - 使用 LoadControl(Type, Object()) 以编程方式加载用户控件

标签 .net vb.net webusercontrol

我正在动态地将 Web 用户控件添加到页面。使用 LoadControl仅采用指向 .ascx 的虚拟路径的方法工作得很好。但是, LoadControl 的过载需要一个类型和一个参数数组让我有些头疼。

Web 用户控件按预期实例化,但 Web 用户控件中包含的控件为空,并且在尝试使用它们时立即出现异常。奇怪,因为它在使用 LoadControl 的第一个版本时有效.

Web 用户控件,简单,带有 Literal控制:

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="MyControl.ascx.vb" Inherits="MyControl" %>
<asp:Literal ID="myLiteral" runat="server"></asp:Literal>

控件背后的代码:
Public Class MyControl
  Inherits System.Web.UI.UserControl

  Public Property Data As MyData  

  Public Sub New()

  End Sub

  Public Sub New(data As MyData)
    Me.Data = data
  End Sub

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    myLiteral.Text = Data.ID ' The Literal is null, but ONLY when I use the second LoadControl() method!
  End Sub

End Class

以及来自.aspx的相关代码我试图从中动态加载控件:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
  Dim x = LoadControl(GetType(MyControl), New Object() {New MyData With {.ID = 117}})
  Page.Controls.Add(x)

  ' Using LoadControl("MyControl.ascx") works as expected!
End Sub

最佳答案

this article 的帮助下通过 Steven Robbins,我最终得到了一个非常方便的扩展方法:

Imports System.Runtime.CompilerServices
Imports System.Web.UI
Imports System.Reflection

Module LoadControls
  <Extension()> _
  Public Function LoadControl(templateControl As TemplateControl, virtualPath As String, ParamArray constructorParams() As Object) As UserControl
    Dim control = TryCast(templateControl.LoadControl(virtualPath), UserControl)
    Dim paramTypes = constructorParams.Select(Function(p) p.GetType()).ToArray
    Dim constructor = control.GetType().BaseType.GetConstructor(paramTypes)

    If constructor Is Nothing Then ' Nothing if no such constructor was found.
      Throw New ArgumentException(String.Format("No constructor for control '{0}' with {1} parameter(s) were found.", virtualPath, paramTypes.Count))
    Else
      constructor.Invoke(control, constructorParams)
    End If

    Return control
  End Function

End Module

关于.net - 使用 LoadControl(Type, Object()) 以编程方式加载用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9446307/

相关文章:

c# - NodeJs 和 signalR 之间的设计考虑

.net - MSTest:断言线程执行

c# - Visual Studio 2015 中的事件列表

vb.net - Oracle 日期字段 - 时间问题

asp.net - Web 用户控件中的外部 JS 文件?

c# - ASP.NET WebForms 使用 IoC 动态加载 WebUserControls

c# - RegEx 替换美元符号之间的文本

.net - 是否使用 SharePoint(作为应用程序开发的基础)(与 ASP.NET 相比)

javascript - 页面加载时调用全屏脚本

javascript - 如何在客户端呈现 WebUserControl