Leer en inglés

Compartir a través de


ToolboxItem Clase

Definición

Proporciona una implementación base de un elemento del cuadro de herramientas.

C#
[System.Serializable]
public class ToolboxItem : System.Runtime.Serialization.ISerializable
C#
public class ToolboxItem : System.Runtime.Serialization.ISerializable
Herencia
ToolboxItem
Derivado
Atributos
Implementaciones

Ejemplos

En el ejemplo de código siguiente se proporciona un componente que usa la IToolboxService interfaz para agregar un controlador de formato de datos de texto, o ToolboxItemCreatorCallback, al cuadro de herramientas. El delegado de devolución de llamada del creador de datos pasa los datos de texto pegados al cuadro de herramientas y arrastrados a un formulario a un personalizado ToolboxItem que crea un TextBox objeto que contiene el texto.

C#
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Security.Permissions;
using System.Windows.Forms;

namespace TextDataTextBoxComponent
{
    // Component that adds a "Text" data format ToolboxItemCreatorCallback 
    // to the Toolbox. This component uses a custom ToolboxItem that 
    // creates a TextBox containing the text data.
    public class TextDataTextBoxComponent : Component
    {
        private bool creatorAdded = false;
        private IToolboxService ts;

        public TextDataTextBoxComponent()
        {                     
        }

        // ISite override to register TextBox creator
        public override System.ComponentModel.ISite Site
        {
            get
            {
                return base.Site;
            }
            set
            {
                if( value != null )
                {                    
                    base.Site = value;

                    if (!creatorAdded)
                    {
                        AddTextTextBoxCreator();
                    }
                }
                else
                {
                    if (creatorAdded)
                    {
                        RemoveTextTextBoxCreator();
                    }

                    base.Site = value;             
                }
            }
        }

        // Adds a "Text" data format creator to the toolbox that creates 
        // a textbox from a text fragment pasted to the toolbox.
        private void AddTextTextBoxCreator()
        {
            ts = (IToolboxService)GetService(typeof(IToolboxService));

            if (ts != null) 
            {
                ToolboxItemCreatorCallback textCreator = 
                    new ToolboxItemCreatorCallback(this.CreateTextBoxForText);

                try
                {
                    ts.AddCreator(
                        textCreator, 
                        "Text", 
                        (IDesignerHost)GetService(typeof(IDesignerHost)));

                    creatorAdded = true;
                }
                catch(Exception ex)
                {
                    MessageBox.Show(
                        ex.ToString(), 
                        "Exception Information");
                }                
            }
        }

        // Removes any "Text" data format creator from the toolbox.
        private void RemoveTextTextBoxCreator()
        {
            if (ts != null)             
            {
                ts.RemoveCreator(
                    "Text", 
                    (IDesignerHost)GetService(typeof(IDesignerHost)));            

                creatorAdded = false;
            }
        }

        // ToolboxItemCreatorCallback delegate format method to create 
        // the toolbox item.
        private ToolboxItem CreateTextBoxForText(
            object serializedObject, 
            string format)
        {
            DataObject o = new DataObject((IDataObject)serializedObject);

            string[] formats = o.GetFormats();

            if (o.GetDataPresent("System.String", true))
            {
                string toolboxText = (string)(o.GetData("System.String", true));
                return (new TextToolboxItem(toolboxText));
            }

            return null;
        }

        protected override void Dispose(bool disposing)
        {
            if (creatorAdded)
            {
                RemoveTextTextBoxCreator();
            }
        }        
    }

    // Custom toolbox item creates a TextBox and sets its Text property
    // to the constructor-specified text.
    public class TextToolboxItem : ToolboxItem
    {
        private string text;
        private delegate void SetTextMethodHandler(Control c, string text);

        public TextToolboxItem(string text) : base()
        {
            this.text = text;
        }

        // ToolboxItem.CreateComponentsCore override to create the TextBox 
        // and link a method to set its Text property.
        protected override IComponent[] CreateComponentsCore(IDesignerHost host)
        {
            System.Windows.Forms.TextBox textbox = 
                (TextBox)host.CreateComponent(typeof(TextBox));
                
            // Because the designer resets the text of the textbox, use 
            // a SetTextMethodHandler to set the text to the value of 
            // the text data.
            Control c = host.RootComponent as Control;
            c.BeginInvoke(
                new SetTextMethodHandler(OnSetText), 
                new object[] {textbox, text});
           
            return new System.ComponentModel.IComponent[] { textbox };
        }        

        // Method to set the text property of a TextBox after it is initialized.
        private void OnSetText(Control c, string text) 
        {
            c.Text = text;
        }
    }
}

En el ejemplo de código siguiente se muestra el uso de la ToolboxItem clase como una clase base para una implementación de elemento de cuadro de herramientas personalizada.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Data;
using System.Runtime.Serialization;
using System.Text;
using System.Windows.Forms;

namespace CustomToolboxItem
{
    public class Form1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        private UserControl1 userControl11;
        private System.Windows.Forms.Label label1;

        public Form1()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.userControl11 = new CustomToolboxItem.UserControl1();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(15, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(265, 62);
            this.label1.TabIndex = 0;
            this.label1.Text = "Build the project and drop UserControl1 from the toolbox onto the form.";
            // 
            // userControl11
            // 
            this.userControl11.LabelText = "This is a custom user control.  The text you see here is provided by a custom too" +
                "lbox item when the user control is dropped on the form.";
            this.userControl11.Location = new System.Drawing.Point(74, 81);
            this.userControl11.Name = "userControl11";
            this.userControl11.Padding = new System.Windows.Forms.Padding(6);
            this.userControl11.Size = new System.Drawing.Size(150, 150);
            this.userControl11.TabIndex = 1;
            // 
            // Form1
            // 
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.userControl11);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }

    // Configure this user control to have a custom toolbox item.
    [ToolboxItem(typeof(MyToolboxItem))]
    public class UserControl1 : UserControl
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.Label label1;

        public UserControl1()
        {
            InitializeComponent();
        }

        public string LabelText
        {
            get
            {
                return label1.Text;
            }
            set
            {
                label1.Text = value;
            }
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(6, 6);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(138, 138);
            this.label1.TabIndex = 0;
            this.label1.Text = "This is a custom user control.  " + 
                "The text you see here is provided by a custom toolbox" +
                " item when the user control is dropped on the form.\r\n";
            this.label1.TextAlign = 
                System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // UserControl1
            // 
            this.Controls.Add(this.label1);
            this.Name = "UserControl1";
            this.Padding = new System.Windows.Forms.Padding(6);
            this.ResumeLayout(false);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }

    // Toolbox items must be serializable.
    [Serializable]
    class MyToolboxItem : ToolboxItem
    {
        // The add components dialog in Visual Studio looks for a public
        // constructor that takes a type.
        public MyToolboxItem(Type toolType)
            : base(toolType)
        {
        }

        // And you must provide this special constructor for serialization.
        // If you add additional data to MyToolboxItem that you
        // want to serialize, you may override Deserialize and
        // Serialize methods to add that data.  
        MyToolboxItem(SerializationInfo info, StreamingContext context)
        {
            Deserialize(info, context);
        }

        // Let's override the creation code and pop up a dialog.
        protected override IComponent[] CreateComponentsCore(
            System.ComponentModel.Design.IDesignerHost host, 
            System.Collections.IDictionary defaultValues)
        {
            // Get the string we want to fill in the custom
            // user control.  If the user cancels out of the dialog,
            // return null or an empty array to signify that the 
            // tool creation was canceled.
            using (ToolboxItemDialog d = new ToolboxItemDialog())
            {
                if (d.ShowDialog() == DialogResult.OK)
                {
                    string text = d.CreationText;

                    IComponent[] comps =
                        base.CreateComponentsCore(host, defaultValues);
                    // comps will have a single component: our data type.
                    ((UserControl1)comps[0]).LabelText = text;
                    return comps;
                }
                else
                {
                    return null;
                }
            }
        }
    }

    public class ToolboxItemDialog : Form
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;

        public ToolboxItemDialog()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(10, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(273, 43);
            this.label1.TabIndex = 0;
            this.label1.Text = "Enter the text you would like" + 
                " to have the user control populated with:";
            // 
            // textBox1
            // 
            this.textBox1.AutoSize = false;
            this.textBox1.Location = new System.Drawing.Point(10, 58);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(270, 67);
            this.textBox1.TabIndex = 1;
            this.textBox1.Text = "This is a custom user control.  " + 
                "The text you see here is provided by a custom toolbox" +
                " item when the user control is dropped on the form.";
            // 
            // button1
            // 
            this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.button1.Location = new System.Drawing.Point(124, 131);
            this.button1.Name = "button1";
            this.button1.TabIndex = 2;
            this.button1.Text = "OK";
            // 
            // button2
            // 
            this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.button2.Location = new System.Drawing.Point(205, 131);
            this.button2.Name = "button2";
            this.button2.TabIndex = 3;
            this.button2.Text = "Cancel";
            // 
            // ToolboxItemDialog
            // 
            this.AcceptButton = this.button1;
            this.CancelButton = this.button2;
            this.ClientSize = new System.Drawing.Size(292, 162);
            this.ControlBox = false;
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = 
                System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "ToolboxItemDialog";
            this.Text = "ToolboxItemDialog";
            this.ResumeLayout(false);
        }

        public string CreationText
        {
            get
            {
                return textBox1.Text;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Comentarios

ToolboxItem es una clase base para los elementos del cuadro de herramientas que se pueden mostrar en el cuadro de herramientas de un entorno en tiempo de diseño. Normalmente, un elemento del cuadro de herramientas representa un componente que se va a crear cuando se invoca en un documento en modo de diseño. La ToolboxItem clase proporciona los métodos y propiedades necesarios para proporcionar al cuadro de herramientas las propiedades para mostrar del elemento del cuadro de herramientas, para crear un componente o componentes cuando se usen y para serializarse y deserializarse para la persistencia dentro de la base de datos del cuadro de herramientas.

Una instancia de la ToolboxItem clase se puede configurar con un nombre, un mapa de bits y un tipo para crear, sin crear una clase que derive de ToolboxItem. La ToolboxItem clase también proporciona una clase base para implementaciones de elementos de cuadro de herramientas personalizadas. Un personalizado ToolboxItem puede crear varios componentes. Para implementar un elemento de cuadro de herramientas personalizado, debe derivar de ToolboxItem e invalidar los CreateComponentsCoremétodos , Serializey Deserialize .

Las siguientes propiedades y métodos deben configurarse para que funcione ToolboxItem correctamente:

  • La DisplayName propiedad especifica la etiqueta del elemento del cuadro de herramientas cuando se muestra en un cuadro de herramientas.

  • La TypeName propiedad especifica el nombre completo del tipo del componente que crea el elemento. Si una clase derivada crea varios componentes, la TypeName propiedad puede o no usarse, dependiendo de si una CreateComponentsCore invalidación de método depende del valor de esta propiedad.

  • La AssemblyName propiedad especifica el ensamblado que contiene el tipo de un componente que crea el elemento.

  • La Bitmap propiedad especifica opcionalmente una imagen de mapa de bits que se mostrará junto al nombre para mostrar del elemento del cuadro de herramientas en el cuadro de herramientas.

  • La Filter propiedad contiene opcionalmente cualquier ToolboxItemFilterAttribute objeto que determine si el elemento del cuadro de herramientas se puede usar en un componente determinado.

  • El CreateComponentsCore método devuelve la instancia de componente o las instancias de para insertar dónde se usa esta herramienta.

  • El Serialize método guarda el elemento del cuadro de herramientas en un especificado SerializationInfo.

  • El Deserialize método configura el elemento del cuadro de herramientas a partir de la información de estado contenida en el especificado SerializationInfo.

  • El Initialize método configura el elemento del cuadro de herramientas para crear el tipo de componente especificado, si el CreateComponentsCore método no se ha invalidado para comportarse de forma diferente.

  • La Locked propiedad indica si se pueden cambiar las propiedades del elemento del cuadro de herramientas. Normalmente, un elemento del cuadro de herramientas se bloquea después de agregarlo a un cuadro de herramientas.

  • El Lock método bloquea un elemento del cuadro de herramientas.

  • El CheckUnlocked método produce una excepción si la Locked propiedad es true.

Constructores

ToolboxItem()

Inicializa una nueva instancia de la clase ToolboxItem.

ToolboxItem(Type)

Inicializa una nueva instancia de la clase ToolboxItem que crea el tipo de componente especificado.

Propiedades

AssemblyName

Obtiene o establece el nombre del ensamblado que contiene los tipos que va a crear el elemento de cuadro de herramientas.

Bitmap

Obtiene o establece un mapa de bits que representa el elemento en el cuadro de herramientas.

Company

Obtiene o establece el nombre de la compañía que se va a mostrar para este elemento ToolboxItem.

ComponentType

Obtiene el tipo de componente de este ToolboxItem.

DependentAssemblies

Obtiene o establece AssemblyName del elemento del cuadro de herramientas.

Description

Obtiene o establece la descripción de este ToolboxItem.

DisplayName

Obtiene o establece el nombre en pantalla de este elemento del cuadro de herramientas.

Filter

Obtiene o establece el filtro que determina si el elemento del cuadro de herramientas se puede utilizar en un componente de destino.

IsTransient

Obtiene un valor que indica si el elemento del cuadro de herramientas es transitorio.

Locked

Obtiene un valor que indica si ToolboxItem está bloqueado actualmente.

OriginalBitmap

Obtiene o establece el mapa de bits original que se usará en el cuadro de herramientas de este elemento.

Properties

Obtiene un diccionario de propiedades.

TypeName

Obtiene o establece el nombre completo del tipo de IComponent que crea el elemento del cuadro de herramientas al ser invocado.

Version

Obtiene la versión de este ToolboxItem.

Métodos

CheckUnlocked()

Produce una excepción si el elemento de cuadro de herramientas se encuentra actualmente bloqueado.

CreateComponents()

Crea los componentes que se deben crear según la configuración del elemento de cuadro de herramientas.

CreateComponents(IDesignerHost)

Crea los componentes que se deben crear según la configuración del elemento de cuadro de herramientas, utilizando el host del diseñador especificado.

CreateComponents(IDesignerHost, IDictionary)

Crea los componentes que se deben crear según la configuración del elemento del cuadro de herramientas, utilizando el host del diseñador especificado y los valores predeterminados.

CreateComponentsCore(IDesignerHost)

Crea un componente o una matriz de componentes cuando se invoca al elemento de cuadro de herramientas.

CreateComponentsCore(IDesignerHost, IDictionary)

Crea una matriz de componentes cuando se invoca el elemento del cuadro de herramientas.

Deserialize(SerializationInfo, StreamingContext)

Carga el estado del elemento de cuadro de herramientas a partir del objeto de información de serialización especificado.

Equals(Object)

Determina si dos instancias de ToolboxItem son iguales.

FilterPropertyValue(String, Object)

Filtra un valor de propiedad antes de devolverlo.

GetHashCode()

Devuelve el código hash de esta instancia.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
GetType(IDesignerHost)

Permite el acceso al tipo asociado al elemento del cuadro de herramientas.

GetType(IDesignerHost, AssemblyName, String, Boolean)

Crea una instancia del tipo especificado, utilizando opcionalmente un host de diseñador y un nombre de ensamblado especificados.

Initialize(Type)

Inicializa el elemento del cuadro de herramientas actual con el tipo especificado que se va a crear.

Lock()

Bloquea el elemento del cuadro de herramientas e impide que se cambien sus propiedades.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnComponentsCreated(ToolboxComponentsCreatedEventArgs)

Genera el evento ComponentsCreated.

OnComponentsCreating(ToolboxComponentsCreatingEventArgs)

Genera el evento ComponentsCreating.

Serialize(SerializationInfo, StreamingContext)

Guarda el estado del elemento del cuadro de herramientas en el objeto de información de serialización especificado.

ToString()

Devuelve un valor de tipo String que representa la clase ToolboxItem actual.

ValidatePropertyType(String, Object, Type, Boolean)

Valida que un objeto es de un tipo determinado.

ValidatePropertyValue(String, Object)

Valida una propiedad antes de que sea asignada al diccionario de propiedades.

Eventos

ComponentsCreated

Se produce inmediatamente después de la creación de componentes.

ComponentsCreating

Se produce inmediatamente antes de la creación de componentes.

Implementaciones de interfaz explícitas

Se aplica a

Producto Versiones
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

Consulte también