Joe*_*orn 5 .net asp.net user-controls code-behind .net-2.0
现在这简化了,但是这里有:
我有一个只包含一个*.ascx文件的用户控件.该控件没有代码隐藏:它只是一个包含一些函数的脚本,如下所示:
<%@ Control Language="VB" EnableViewState="False" ClassName="MyControlType" %>
<script runat="server">
Public Function MyFunction() As String
return "CalledMyFunction!"
End Function
</script>
Run Code Online (Sandbox Code Playgroud)
这是整个文件.我可以使用这样的标记成功地将此控件添加到aspx页面:
<%@ Register Src="~/path/to/Control.ascx" TagPrefix="aaa" TagName="MyControl" %>
...
<aaa:MyControl runat="server" id="MyControl1" />
Run Code Online (Sandbox Code Playgroud)
现在我要做的是从页面的代码隐藏中调用MyFunction,如下所示:
Dim someString As String = MyControl1.MyFunction()
Run Code Online (Sandbox Code Playgroud)
不幸的是,我做不到.相反,我得到编译错误的效果" 'MyFunction' is not a member of 'System.Web.UI.UserControl'.
"
我也试过这个:
Dim someString As String = DirectCast(MyControl1, MyControlType).MyFunction()
Run Code Online (Sandbox Code Playgroud)
然后编译器告诉我," Type 'MyControlType' is not defined.
"
我玩过很多次,但我无法让它发挥作用.将MyControl1转换为更精确类型的所有努力都失败了,其他解决办法也是如此.我怀疑问题是没有代码隐藏的ascx文件无法编译到程序集,但代码隐藏需要编译到程序集,因此编译器对控件的类型感到困惑.
为了能够调用该函数,我需要做什么?
[编辑]
所以我只需要为用户控件添加代码隐藏.无论如何,这就是我想要做的.不过,我仍然想知道如何在不需要的情况下做到这一点.
确保代码隐藏中的 MyControl1 对象属于 MyControlType 类型,并且在调用该函数时进行了强制转换。编译器指出它在 UserControl 的基类中找不到方法 MyFunction()。