Udostępnij za pośrednictwem


How to: Extend Component Containers

Component containers are completely extensible. You can inherit from the Container class and add properties or methods, add custom functionality to enforce rules, override base methods, or any other custom functionality you want your container to incorporate. For details on containers and extending containers, see Containers, Sites, and Components.

You extend a Container as you would extend any base class. You create a class that inherits the properties of the base class, override any base methods that you want to extend, and add any additional properties or methods that you need. You can then use your new class as you would a standard Container and use any of the new functionality you have encoded.

To extend the Container base class

  1. Declare a new class that inherits from the Container class.

    Public Class myContainer
       Inherits System.ComponentModel.Container
    End Class
    
    class myContainer: System.ComponentModel.Container
    {
    }
    
    class myContainer
       extends System.ComponentModel.Container
    {
    }
    
  2. Override any base-class methods to add additional functionality. The following example shows how to override the Add method.

    Note

    The Container actually has two overloads of Add, and in this example, you would want to provide an override of each.

    ' Because Add is overloaded, this line includes the Overloads keyword.
    Public Overloads Overrides Sub Add(ByVal component As _
       System.ComponentModel.IComponent)
       ' Determines if the component can be added to the container.
       If TypeOf component Is Widget Then
          ' Calls the base Add function to add the component.
          MyBase.Add(component)
       Else
          ' Throws an exception.
          Throw New NonWidgetException()
       End If
    End Sub
    
    public override void Add(System.ComponentModel.IComponent component)
    {
       if (component is Widget)
          base.Add(component);
       else 
       {
          throw(new NonWidgetException());
       }
    }
    
    public void Add(System.ComponentModel.IComponent component)
       throws NonWidgetException
    {
       if ( component instanceof Widget  ) {
          super.Add(component);
       }
       else
       {
          throw new NonWidgetException() ;
       }
    }
    
  3. Add any new properties or methods you want your new container to incorporate. For details, see Class Properties, Fields, and Methods.

See Also

Tasks

How to: Create Component Containers

Concepts

Containers, Sites, and Components

Communication Between Containers and Components

Reference

Container