ASP.NET web control only allow specific contents?
I am new to ASP .N开发者_高级运维ET web controls, but not ASP .NET in general or C#.
I am wondering how I can limit the allowed content types to a specific class.
I have made a custom web control called TabPanel, and I want it to only be able to contain TabPages.
As an example, the following markup should be illegal, since it contains a checkbox.
<cc1:TabPanel ID="TabPanel1" runat="server">
<cc1:TabPage runat="server">
this is a simple test
</cc1:TabPage>
<cc1:TabPage runat="server">
this is another simple test
</cc1:TabPage>
<asp:CheckBox runat="server" />
</cc1:TabPanel>
In this case, I wouldn't want the checkbox to be there. How can I block this from happening?
I have not tried exactly what you are after but based on other things I have done I would try this:
- Create a property in TabPannel that is a collection of TabPages (call it Tabs for demonstration purposes). This can be an array, a list, or a custom collection class, the key is to have typed to only accept TabPages as members.
- Give the property the [PersistenceMode(PersistenceMode.InnerProperty)] atribute.
- Override CreateChildControls to add the contents of the collection to the control.
If you do it this way then your mark up should end up looking something like this:
<cc1:TabPanel ID="TabPanel1" runat="server">
<Tabs>
<cc1:TabPage runat="server">this is a simple test</cc1:TabPage>
<cc1:TabPage runat="server">this is another simple test</cc1:TabPage>
</Tabs>
</cc1:TabPanel>
and it should not allow anything that is not a TabPage to be nested inside of the Tabs property.
http://msdn.microsoft.com/en-us/library/9txe1d4x(v=VS.90).aspx is a walk through demonstrating this technique in detail.
I figured it out.
Had to throw an exception under AddedControl procedure that I overrided from the WebControl if the type of the control being added was not of the type I wanted.
Now the designer shows a beautiful red error-message on the control itself, preventing me from doing such a foolish thing.
Awesome!
I'm going to take a guess here, but based on some quick googling I think you're looking for the ControlBuilder. The demo limits their control to an object called "mycell", but I don't see any reason why this couldn't be limited to your own objects, or build-in ASP.NET controls (i.e. Panels but not TextBoxes, etc.)
As a last resort, I'm sure you could hijack the rendering method and only render controls within the pre-determined class set, but this seems hack-ish at best.
精彩评论