.NET用户/服务器控件与自定义列表项

时间:2011-02-18 20:13:13

标签: asp.net vb.net visual-studio-2010 user-controls

我正在尝试创建一个简单的菜单用户控件,如概述here

附加的代码导致“对象引用未设置为对象的实例”错误,但我无法弄清楚原因。有什么想法吗?

<%@ Master Language="VB" CodeFile="MySite.master.vb" Inherits="MySite" %>
<%@ Register src="Controls/Menu.ascx" tagname="Menu" tagprefix="my"  %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MySite</title>
    <link href="Styles/MySite.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder id="headContent" runat="server">
    </asp:ContentPlaceHolder>    
</head>
<body id="masterBody" runat="server">
    <form id="form1" runat="server">
        <my:Menu ID="Menu1" runat="server">
            <MenuItems>
                <my:MenuItem Text="Test" NavigateUrl="~/Default.aspx" />
            </MenuItems>
         </my:Menu>
    </form>
</body>
</html>

Partial Class Controls_Menu
        Inherits System.Web.UI.UserControl

    Private m_Items As List(Of MenuItem) = Nothing
        <PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property MenuItems() As List(Of MenuItem)
            Get
                Return m_Items
            End Get
            Set(ByVal value As List(Of MenuItem))
                m_Items = value
            End Set
        End Property

    End Class

    Public Class MenuItem
        Private m_Text As String
        Public Property Text() As String
            Get
                Return m_Text
            End Get
            Set(ByVal value As String)

            End Set
        End Property
        Private m_NavigateUrl As String
        Public Property NavigateUrl() As String
            Get
                Return m_NavigateUrl
            End Get
            Set(ByVal value As String)
                m_NavigateUrl = value
            End Set
        End Property
    End Class

1 个答案:

答案 0 :(得分:0)

问题在于:

<MenuItems>
     <my:MenuItem Text="Test" NavigateUrl="~/Default.aspx" />
</MenuItems>

ASP.net正在尝试添加到您的MenuItems列表,它通过调用

来完成此操作
MenuItems.Add(...)

但是,由于m_Items等于Nothing,因此会出现错误。要修复此替换

Private m_Items As List(Of MenuItem) = Nothing

使用

Private m_Items As List(Of MenuItem) = New List(Of MenuItem)()