【问题标题】:ASP.NET Custom control, is it possible to restrict contents of a template?ASP.NET 自定义控件,是否可以限制模板的内容?
【发布时间】:2011-03-04 01:53:00
【问题描述】:

一些 ASP.NET 控件只允许某些类型的项目,例如:

<uc:MyControl runat="server"....>

<MyTableTemplate>
  <MyTableRow .... />
  <MyTableRow .... />
  <MyTableRow .... />
</MyTableTemplate>

</uc:MyControl>

我正在尝试在我自己的自定义控件中重新创建它,这样您就只能将 MyTableRow 对象放入模板中,而 Visual Studio 将阻止设计者放入其他任何东西。

我一直在查看 ControlBuilder 课程,但我不能完全确定它是否符合我的要求。此外,示例没有提到我上面的嵌套,其中 MyTableRow 的数组位于另一个模板字段中。

有谁知道如何做到这一点?

编辑:UpdatePanel 似乎是这样工作的:如果您这样声明 UpdatePanel:

<asp:UpdatePanel>
<Triggers>

</Triggers>
</asp:UpdatePanel>

除了 intellisense 中列出的两个特定控件之外,您不能在 Triggers 部分中放置任何内容,如果您尝试,则会收到设计时错误。这正是我想要模仿的行为。

====

我尝试执行 Alex 的建议,这是我的代码:

public partial class MyControl : System.Web.UI.UserControl
{
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ActionButtonCollection ActionButtons
    {
        get;
        set;
    }
}


public class ActionButtonCollection : Collection<ActionButton>
{

}

public abstract class ActionButtonBase
{
    public string Test { get; set; }
}

public class ActionButton : ActionButtonBase
{

}

然而,这段代码里面没有智能感知

<uc:MyCustomControl runat="server">
<ActionButtons>

</ActionButtons>
</uc:MyCustomControl >

【问题讨论】:

    标签: asp.net custom-controls


    【解决方案1】:

    编辑:添加了指向google docs的示例链接。

    首先,构建网站,然后您就可以将此控件与 IntelliSense 一起使用。

    实际上,UpdatePanel&lt;Triggers&gt; 属性不是模板。它只是对象的集合。你可以通过声明你自己的类和一个继承Collection&lt;YourClass&gt;的类来实现这一点;然后只需将Collection&lt;YourClass&gt; 类型的公共属性添加到您的控件中,您就可以归档“更新面板触发器”行为。

    这是一个例子:

    public abstract class UpdatePanelTrigger
    {
        public string ControlId { get; set; }
    }
    
    public class UpdatePanelTrigger1 : UpdatePanelTrigger
    {
    
    }
    
    public class UpdatePanelTrigger2 : UpdatePanelTrigger
    {
    
    }
    
    public class UpdatePanelTriggerCollection : Collection<UpdatePanelTrigger>
    {
    
    }
    

    最后,您的控制:

    public class MyControl : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public UpdatePanelTriggerCollection Triggers { get; set; }
    }
    

    然后你可以在你的页面上使用它:

    <my:MyControl runat="Server">
        <Triggers>
            <my:UpdatePanelTrigger1 ControlId="ctrl1" />
            <my:UpdatePanelTrigger2 ControlId="ctrl2" />
        </Triggers>
    </my:MyControl>
    

    顺便说一句,除了从 UpdatePanelTrigger 类继承的类型之外,您不能将任何内容放入 Triggers 部分。

    【讨论】:

    • 我已经尝试过了,但是当我将光标放在 之间并输入
    • 啊哈,我需要 [PersistenceMode(PersistenceMode.InnerProperty)] 周围的 Collection&lt;UpdatePanelTrigger&gt;,所以我没有从它继承,而是将它添加为属性。
    • 我无法访问属性 ControlId
    • 它不适合我,ActionButton 上也没有名为 test 的属性...
    • @Alex:我不确定......如果我创建集合 [PersistenceMode(PersistenceMode.InnerProperty)] 我会得到 ActionButton 但它仍然没有任何属性。我也在使用 .NET 4,这是我能想到的唯一其他区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    相关资源
    最近更新 更多