Comparteix a través de


ControlPersister Clase

Definición

Proporciona métodos para almacenar controles de servidor Web en tiempo de diseño.

public ref class ControlPersister sealed
public sealed class ControlPersister
type ControlPersister = class
Public NotInheritable Class ControlPersister
Herencia
ControlPersister

Ejemplos

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Web.dll>
#using <System.Design.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Design;
using namespace System::IO;
using namespace System::Web::UI;
using namespace System::Web::UI::Design;
using namespace System::Web::UI::WebControls;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Windows::Forms;
using namespace System::Windows::Forms::Design;

// Provides a form with a multiline text box display.
private ref class StringDisplayForm: public Form
{
public:
   StringDisplayForm( String^ displayText )
   {
      this->Size = System::Drawing::Size( 400, 400 );
      this->Text = "Control Persistence String";
      this->SuspendLayout();
      System::Windows::Forms::TextBox^ tbox = gcnew System::Windows::Forms::TextBox;
      tbox->Multiline = true;
      tbox->Size = System::Drawing::Size( this->Width - 40, this->Height - 90 );
      tbox->Text = displayText;
      this->Controls->Add( tbox );
      System::Windows::Forms::Button^ okButton = gcnew System::Windows::Forms::Button;
      okButton->Text = "OK";
      okButton->Size = System::Drawing::Size( 80, 24 );
      okButton->Location = Point(this->Width - 100,this->Height - 60);
      okButton->Anchor = AnchorStyles(AnchorStyles::Bottom | AnchorStyles::Right);
      okButton->DialogResult = ::DialogResult::OK;
      this->Controls->Add( okButton );
      this->ResumeLayout();
   }

};

// Provides a form with a list for selection.
private ref class ControlSelectionForm: public Form
{
private:
   array<System::Web::UI::Control^>^controlArray;

public:
   System::Windows::Forms::ListBox^ controlList;
   ControlSelectionForm( array<System::Web::UI::Control^>^controlArray )
   {
      this->controlArray = controlArray;
      this->Size = System::Drawing::Size( 400, 500 );
      this->Text = "Control Persister Selection Form";
      this->SuspendLayout();
      System::Windows::Forms::Label ^ label1 = gcnew System::Windows::Forms::Label;
      label1->Text = "Select the control to persist:";
      label1->Size = System::Drawing::Size( 240, 20 );
      label1->Location = Point(10,10);
      this->Controls->Add( label1 );
      controlList = gcnew System::Windows::Forms::ListBox;
      controlList->Size = System::Drawing::Size( 370, 400 );
      controlList->Location = Point(10,30);
      controlList->Anchor = AnchorStyles(AnchorStyles::Left | AnchorStyles::Top | AnchorStyles::Bottom | AnchorStyles::Right);
      this->Controls->Add( controlList );
      System::Windows::Forms::Button^ okButton = gcnew System::Windows::Forms::Button;
      okButton->Text = "OK";
      okButton->Size = System::Drawing::Size( 80, 24 );
      okButton->Location = Point(this->Width - 100,this->Height - 60);
      okButton->Anchor = AnchorStyles(AnchorStyles::Bottom | AnchorStyles::Right);
      okButton->DialogResult = ::DialogResult::OK;
      this->Controls->Add( okButton );
      System::Windows::Forms::Button^ cancelButton = gcnew System::Windows::Forms::Button;
      cancelButton->Text = "Cancel";
      cancelButton->Size = System::Drawing::Size( 80, 24 );
      cancelButton->Location = Point(this->Width - 200,this->Height - 60);
      cancelButton->Anchor = AnchorStyles(AnchorStyles::Bottom | AnchorStyles::Right);
      cancelButton->DialogResult = ::DialogResult::Cancel;
      this->Controls->Add( cancelButton );
      for ( int i = 0; i < controlArray->Length; i++ )
         controlList->Items->Add( controlArray[ i ]->UniqueID );
      this->ResumeLayout();
   }
};

// Provides a form with a multiline text box for input.
private ref class StringInputForm: public Form
{
public:
   System::Windows::Forms::TextBox^ tbox;
   StringInputForm()
   {
      this->Size = System::Drawing::Size( 400, 400 );
      this->Text = "Input Control Persistence String";
      this->SuspendLayout();
      tbox = gcnew System::Windows::Forms::TextBox;
      tbox->Multiline = true;
      tbox->Size = System::Drawing::Size( this->Width - 40, this->Height - 90 );
      tbox->Text = "";
      this->Controls->Add( tbox );
      System::Windows::Forms::Button^ okButton = gcnew System::Windows::Forms::Button;
      okButton->Text = "OK";
      okButton->Size = System::Drawing::Size( 80, 24 );
      okButton->Location = Point(this->Width - 100,this->Height - 60);
      okButton->Anchor = AnchorStyles(AnchorStyles::Bottom | AnchorStyles::Right);
      okButton->DialogResult = ::DialogResult::OK;
      this->Controls->Add( okButton );
      System::Windows::Forms::Button^ cancelButton = gcnew System::Windows::Forms::Button;
      cancelButton->Text = "Cancel";
      cancelButton->Size = System::Drawing::Size( 80, 24 );
      cancelButton->Location = Point(this->Width - 200,this->Height - 60);
      cancelButton->Anchor = AnchorStyles(AnchorStyles::Bottom | AnchorStyles::Right);
      cancelButton->DialogResult = ::DialogResult::Cancel;
      this->Controls->Add( cancelButton );
      this->ResumeLayout();
   }
};


// Web control designer provides an interface
// to use the ControlPersister and ControlParser.
public ref class ControlParserPersisterDesigner: public System::Web::UI::Design::ControlDesigner
{
public:
   ControlParserPersisterDesigner()
      : ControlDesigner()
   {}

   property System::ComponentModel::Design::DesignerVerbCollection^ Verbs 
   {
      // Provides designer verb menu commands to
      // persist a control and to load a persisted control.
      [System::Security::Permissions::PermissionSetAttribute(System::Security::Permissions::SecurityAction::Demand, Name="FullTrust")]
      virtual System::ComponentModel::Design::DesignerVerbCollection^ get() override
      {
         DesignerVerbCollection^ dvc = gcnew DesignerVerbCollection;
         dvc->Add( gcnew DesignerVerb( "Load Persisted Control...",gcnew EventHandler( this, &ControlParserPersisterDesigner::loadPersistedControl ) ) );
         dvc->Add( gcnew DesignerVerb( "Parse and Save Control...",gcnew EventHandler( this, &ControlParserPersisterDesigner::saveControl ) ) );
         return dvc;
      }

   }

private:

   // Displays a textbox form to receive an HTML
   // String* that represents a control, and creates
   // a toolbox item for the control, if not already
   // present in the selected toolbox category.
   void loadPersistedControl( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      // Display a StringInputForm to obtain a persisted control String*.
      StringInputForm^ inputForm = gcnew StringInputForm;
      if ( inputForm->ShowDialog() != DialogResult::OK )
            return;

      if ( inputForm->tbox->Text->Length < 2 )
            return;

      // Obtain an IDesignerHost* for the design-mode document.
      IDesignerHost^ host = dynamic_cast<IDesignerHost^>(this->Component->Site->GetService( IDesignerHost::typeid ));
      
      // Create a Web control from the persisted control String*.
      System::Web::UI::Control^ ctrl = ControlParser::ParseControl( host, inputForm->tbox->Text->Trim() );

      // Create a Web control toolbox item for the type of the control
      WebControlToolboxItem^ item = gcnew WebControlToolboxItem( ctrl->GetType() );
      
      // Add the Web control toolbox item to the toolbox
      IToolboxService^ toolService = dynamic_cast<IToolboxService^>(this->Component->Site->GetService( IToolboxService::typeid ));
      if ( toolService != nullptr )
            toolService->AddToolboxItem( item );
      else
            throw gcnew Exception( "IToolboxService* was not found." );
   }

   // Displays a list of controls in the project, if any,
   // and displays the HTML representing the persisted, selected control.
   void saveControl( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      // Get the collection of components in the current
      // design mode document.
      ComponentCollection^ documentComponents = this->Component->Site->Container->Components;

      // Filter the components to those that derive from the
      // System::Web::UI::Control class.
      // Create an IComponent* array of the maximum possible length needed.
      array<IComponent^>^filterArray = gcnew array<IComponent^>(documentComponents->Count);

      // Count the total qualifying components.
      int total = 0;
      for ( int i = 0; i < documentComponents->Count; i++ )
      {
         // If the component derives from System::Web::UI::Control,
         // copy a reference to the control to the filterArray
         // array and increment the control count.
         if ( System::Web::UI::Control::typeid->IsAssignableFrom( documentComponents[i]->GetType() ) )
         {
            if ( (dynamic_cast<System::Web::UI::Control^>(documentComponents[i]))->UniqueID != nullptr )
            {
               filterArray[total] = documentComponents[i];
               total++;
            }
         }

      }
      if ( total == 0 )
            throw gcnew Exception( "Document contains no System::Web::UI::Control components." );

      // Move the components that derive from System::Web::UI::Control to a
      // new array of the correct size.
      array<System::Web::UI::Control^>^controlArray = gcnew array<System::Web::UI::Control^>(total);
      for ( int i = 0; i < total; i++ )
         controlArray[i] = dynamic_cast<System::Web::UI::Control^>(filterArray[i]);

      // Create a ControlSelectionForm to provide a persistence
      // configuration interface.
      ControlSelectionForm^ selectionForm = gcnew ControlSelectionForm( controlArray );

      // Display the form.
      if ( selectionForm->ShowDialog() != DialogResult::OK )
            return;

      // Validate the selection.
      if ( selectionForm->controlList->SelectedIndex == -1 )
            throw gcnew Exception( "You must select a control to persist." );

      // Parse the selected control.
      String^ persistedData = ControlPersister::PersistControl( controlArray[ selectionForm->controlList->SelectedIndex ] );

      // Display the control persistence String* in a text box.
      StringDisplayForm^ displayForm = gcnew StringDisplayForm( persistedData );
      displayForm->ShowDialog();
   }
};

// Simple text display control hosts the ControlParserPersisterDesigner.

[DesignerAttribute(ControlParserPersisterDesigner::typeid,IDesigner::typeid)]
public ref class ControlParserPersisterDesignerControl: public WebControl
{
private:
   String^ text;

public:

   property String^ Text 
   {
      [Bindable(true),
      Category("Appearance"),
      DefaultValue("")]
      String^ get()
      {
         return text;
      }

      void set( String^ value )
      {
         text = value;
      }
   }
   ControlParserPersisterDesignerControl()
      : WebControl()
   {
      text = "Right-click here to access control persistence methods in design mode";
   }

protected:
   virtual void Render( HtmlTextWriter^ output ) override
   {
      output->Write( Text );
   }
};
using System;
using System.Drawing;
using System.Drawing.Design;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace ControlParserPersisterDesignerControl_CS
{
    // Web control designer provides an interface 
    //   to use the ControlPersister and ControlParser.
    // The DesignerActionListCollection must run under "FullTrust",
    //   so you must also require your designer to run under "FullTrust".
    [System.Security.Permissions.PermissionSetAttribute(
        System.Security.Permissions.SecurityAction.InheritanceDemand, 
        Name = "FullTrust")]
    [System.Security.Permissions.PermissionSetAttribute(
        System.Security.Permissions.SecurityAction.Demand, 
        Name = "FullTrust")]
    public class ControlParserPersisterDesigner :
        System.Web.UI.Design.ControlDesigner
    {
        private DesignerActionListCollection _actLists = null;

        public ControlParserPersisterDesigner()
            : base()
        {}

        // Creates designer menu commands to persist
        // a control and to load a persisted control.
        public override DesignerActionListCollection ActionLists
        {
            get
            {
                if (_actLists == null)
                {
                    _actLists = new DesignerActionListCollection();
                    _actLists.AddRange(base.ActionLists);
                    _actLists.Add(new ParserActionList(this));
                }
                return _actLists;
            }
        }

        // A custom class for the DesignerActionList
        private class ParserActionList : DesignerActionList
        {
            private ControlParserPersisterDesigner _parent;
            private DesignerActionItemCollection _items;

            public ParserActionList(ControlParserPersisterDesigner parent) : 
                base(parent.Component)
            {
                _parent = parent;
            }

            public override DesignerActionItemCollection GetSortedActionItems()
            {
                if (_items == null)
                {
                    // Create the collection
                    _items = new DesignerActionItemCollection();

                    _items.Add(new DesignerActionMethodItem(this, "saveControl", "Parse and Save Control...", true));
                    _items.Add(new DesignerActionMethodItem(this, "loadPersistedControl", "Load Persisted Control...", true));
                }
                return _items;
            }

            // Displays a list of controls in the project, if any,
            // and displays the HTML markup for the selected control.       
            private void saveControl()
            {
                // Get the collection of components in the current 
                // design mode document.
                ComponentCollection documentComponents =
                    this.Component.Site.Container.Components;

                // Filter the components to those that derive from the 
                // System.Web.UI.Control class.

                // Create an IComponent array of the maximum possible length needed.
                IComponent[] filterArray = new IComponent[documentComponents.Count];

                // Count the total qualifying components.
                int total = 0;
                for (int i = 0; i < documentComponents.Count; i++)
                {
                    // If the component derives from System.Web.UI.Control, 
                    // copy a reference to the control to the filterArray 
                    // array and increment the control count.
                    if (typeof(System.Web.UI.Control).IsAssignableFrom(
                        documentComponents[i].GetType()))
                    {
                        if (((System.Web.UI.Control)documentComponents[i]).UniqueID
                            != null)
                        {
                            filterArray[total] = documentComponents[i];
                            total++;
                        }
                    }
                }

                if (total == 0)
                    throw new Exception(
                        "Document contains no System.Web.UI.Control components.");

                // Move the components that derive from System.Web.UI.Control to a 
                // new array of the correct size.
                System.Web.UI.Control[] controlArray =
                    new System.Web.UI.Control[total];
                for (int i = 0; i < total; i++)
                    controlArray[i] = (System.Web.UI.Control)filterArray[i];

                // Create a ControlSelectionForm to select a control.
                ControlSelectionForm selectionForm =
                    new ControlSelectionForm(controlArray);

                // Display the form.
                if (selectionForm.ShowDialog() != DialogResult.OK)
                    return;

                // Validate the selection.
                if (selectionForm.controlList.SelectedIndex == -1)
                    throw new Exception("You must select a control to persist.");

                // Parse the selected control into a persistence string.
                string persistedData = ControlPersister.PersistControl(
                    controlArray[selectionForm.controlList.SelectedIndex]);

                // Display the persistence string in a text box.
                StringDisplayForm displayForm =
                    new StringDisplayForm(persistedData);
                displayForm.ShowDialog();
            }

            // Displays a textbox form to receive an HTML 
            // string that represents a control, and creates
            // a toolbox item for the control, if not already
            // present in the selected toolbox category.
            private void loadPersistedControl()
            {
                // Display a StringInputForm to obtain a persisted control string.
                StringInputForm inputForm = new StringInputForm();

                if (inputForm.ShowDialog() != DialogResult.OK)
                    return;
                if (inputForm.TBox.Text.Length < 2)
                    return;

                // Obtain an IDesignerHost for the design-mode document.
                IDesignerHost host = (IDesignerHost)
                    this.Component.Site.GetService(typeof(IDesignerHost));

                // Create a Web control from the HTML markup.
                System.Web.UI.Control ctrl =
                    ControlParser.ParseControl(host, inputForm.TBox.Text.Trim());

                // Create a Web control toolbox item for the type of the control
                System.Web.UI.Design.WebControlToolboxItem item =
                    new System.Web.UI.Design.WebControlToolboxItem(ctrl.GetType());

                // Add the Web control toolbox item to the toolbox
                IToolboxService toolService = (IToolboxService)
                    this.Component.Site.GetService(typeof(IToolboxService));
                if (toolService != null)
                    toolService.AddToolboxItem(item);
                else
                    throw new Exception("IToolboxService was not found.");
            }
        }
    }

    // Simple text display control hosts the ControlParserPersisterDesigner.
    [DesignerAttribute(typeof(ControlParserPersisterDesigner),
         typeof(IDesigner))]
    public class ControlParserPersisterDesignerControl :
        System.Web.UI.WebControls.WebControl
    {
        private string _text;

        [Bindable(true),
            Category("Appearance"),
            DefaultValue("")]
        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        public ControlParserPersisterDesignerControl()
            : base()
        {
            _text = "Right-click here to access control persistence " +
                "methods in design mode";
        }

        protected override void Render(HtmlTextWriter output)
        {
            output.Write(Text);
        }
    }

    // Provides a form with a list for selection.
    internal class ControlSelectionForm : Form
    {
        private System.Web.UI.Control[] controlArray;
        public System.Windows.Forms.ListBox controlList;

        public ControlSelectionForm(System.Web.UI.Control[] controlArray)
        {
            this.controlArray = controlArray;

            this.Size = new Size(400, 500);
            this.Text = "Control Selection Form";

            this.SuspendLayout();

            System.Windows.Forms.Label label1 =
                new System.Windows.Forms.Label();
            label1.Text = "Select a control to parse:";
            label1.Size = new Size(240, 20);
            label1.Location = new Point(10, 10);
            this.Controls.Add(label1);

            controlList = new System.Windows.Forms.ListBox();
            controlList.Size = new Size(370, 400);
            controlList.Location = new Point(10, 30);
            controlList.Anchor = AnchorStyles.Left | AnchorStyles.Top |
                AnchorStyles.Bottom | AnchorStyles.Right;
            this.Controls.Add(controlList);

            System.Windows.Forms.Button okButton =
                new System.Windows.Forms.Button();
            okButton.Text = "OK";
            okButton.Size = new Size(80, 24);
            okButton.Location =
                new Point(this.Width - 100, this.Height - 60);
            okButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            okButton.DialogResult = DialogResult.OK;
            this.Controls.Add(okButton);

            System.Windows.Forms.Button cancelButton =
                new System.Windows.Forms.Button();
            cancelButton.Text = "Cancel";
            cancelButton.Size = new Size(80, 24);
            cancelButton.Location =
                new Point(this.Width - 200, this.Height - 60);
            cancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            cancelButton.DialogResult = DialogResult.Cancel;
            this.Controls.Add(cancelButton);

            for (int i = 0; i < controlArray.Length; i++)
                controlList.Items.Add(controlArray[i].UniqueID);

            this.ResumeLayout();
        }
    }

    // Provides a form with a multiline text box display.
    internal class StringDisplayForm : Form
    {
        private System.Windows.Forms.TextBox tbox = 
            new System.Windows.Forms.TextBox();

        public System.Windows.Forms.TextBox TBox
        {
            get { return tbox; }
            set { tbox = value; }
        }

        public StringDisplayForm(string displayText)
        {
            this.Size = new Size(400, 300);
            this.Text = "Control Persistence String";

            this.SuspendLayout();
            TBox.Multiline = true;
            TBox.Size = new Size(this.Width - 40, this.Height - 90);
            TBox.Text = displayText;
            this.Controls.Add(TBox);

            System.Windows.Forms.Button okButton =
                new System.Windows.Forms.Button();
            okButton.Text = "OK";
            okButton.Size = new Size(80, 24);
            okButton.Location =
                new Point(this.Width - 100, this.Height - 60);
            okButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            okButton.DialogResult = DialogResult.OK;
            this.Controls.Add(okButton);

            this.ResumeLayout();
        }
    }

    // Provides a form with a multiline text box for input.
    internal class StringInputForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.TextBox tbox = 
            new System.Windows.Forms.TextBox();

        public System.Windows.Forms.TextBox TBox
        {
            get { return tbox; }
        }

        public StringInputForm()
        {
            this.Size = new Size(400, 300);
            this.Text = "Input Control Persistence String";

            this.SuspendLayout();
            tbox = new System.Windows.Forms.TextBox();
            tbox.Multiline = true;
            tbox.Size = new Size(this.Width - 40, this.Height - 90);
            tbox.Text = "";
            this.Controls.Add(tbox);

            System.Windows.Forms.Button okButton =
                new System.Windows.Forms.Button();
            okButton.Text = "OK";
            okButton.Size = new Size(80, 24);
            okButton.Location =
                new Point(this.Width - 100, this.Height - 60);
            okButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            okButton.DialogResult = DialogResult.OK;
            this.Controls.Add(okButton);

            System.Windows.Forms.Button cancelButton =
                new System.Windows.Forms.Button();
            cancelButton.Text = "Cancel";
            cancelButton.Size = new Size(80, 24);
            cancelButton.Location =
                new Point(this.Width - 200, this.Height - 60);
            cancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            cancelButton.DialogResult = DialogResult.Cancel;
            this.Controls.Add(cancelButton);

            this.ResumeLayout();
        }
    }
}
Imports System.Drawing
Imports System.Drawing.Design
Imports System.Web.UI
Imports System.Web.UI.Design
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Windows.Forms
Imports System.Windows.Forms.Design

Namespace ControlParserPersisterDesignerControl_VB

    ' Web control designer provides an interface 
    '   to use the ControlPersister and ControlParser.
    ' The DesignerActionListCollection must run under "FullTrust",
    '   so you must also require your designer to run under "FullTrust".
    <System.Security.Permissions.PermissionSetAttribute( _
        System.Security.Permissions.SecurityAction.InheritanceDemand, _
        Name:="FullTrust")> _
    <System.Security.Permissions.PermissionSetAttribute( _
         Security.Permissions.SecurityAction.Demand, _
         Name:="FullTrust")> _
    Public Class ControlParserPersisterDesigner
        Inherits System.Web.UI.Design.ControlDesigner

        Private _actLists As DesignerActionListCollection

        Public Sub New()
        End Sub

        ' Creates designer menu commands to persist 
        ' a control and to load a persisted control.
        Public Overrides ReadOnly Property ActionLists() As System.ComponentModel.Design.DesignerActionListCollection
            Get
                If IsNothing(_actLists) Then
                    _actLists = New DesignerActionListCollection()
                    _actLists.AddRange(MyBase.ActionLists)
                    _actLists.Add(New ParserActionList(Me))
                End If

                Return _actLists
            End Get
        End Property
        'Public Overrides ReadOnly Property Verbs() _
        'As System.ComponentModel.Design.DesignerVerbCollection
        '    Get
        '        Dim dvc As New DesignerVerbCollection()
        '        dvc.Add(New DesignerVerb("Load Persisted Control...", _
        '            New EventHandler(AddressOf Me.loadPersistedControl)))
        '        dvc.Add(New DesignerVerb("Parse and Save Control...", _
        '            New EventHandler(AddressOf Me.saveControl)))
        '        Return dvc
        '    End Get
        'End Property

        ' Displays a textbox form to receive an HTML 
        ' string that represents a control, and creates
        ' a toolbox item for the control, if not already
        ' present in the selected toolbox category.

        Private Class ParserActionList
            Inherits DesignerActionList

            Private _parent As ControlParserPersisterDesigner
            Private _items As DesignerActionItemCollection

            Public Sub New(ByVal parent As ControlParserPersisterDesigner)
                MyBase.New(parent.Component)
                _parent = parent
            End Sub

            Public Overrides Function GetSortedActionItems() As System.ComponentModel.Design.DesignerActionItemCollection
                If IsNothing(_items) Then
                    _items = New DesignerActionItemCollection()
                    _items.Add(New DesignerActionMethodItem(Me, "saveControl", "Parse and Save Control...", True))
                    _items.Add(New DesignerActionMethodItem(Me, "loadPersistedControl", "Load Persisted Control...", True))
                End If
                Return _items
            End Function

            ' Displays a list of controls in the project, if any,
            ' and displays the HTML markup for the selected control.       
            Private Sub saveControl()
                ' Get the collection of components in the current 
                ' design mode document.
                Dim documentComponents As ComponentCollection = _
                    Me.Component.Site.Container.Components

                ' Filter the components to those that derive from the 
                ' System.Web.UI.Control class.

                ' Create an IComponent array of the maximum possible length needed.
                Dim filterArray(documentComponents.Count) As IComponent

                ' Count the total qualifying components.
                Dim total As Integer = 0
                Dim i As Integer
                For i = 0 To documentComponents.Count - 1
                    ' If the component derives from System.Web.UI.Control, 
                    ' copy a reference to the control to the filterArray 
                    ' array and increment the control count.
                    If GetType(System.Web.UI.Control).IsAssignableFrom(CType(documentComponents(i), Object).GetType()) Then
                        If Not (CType(documentComponents(i), System.Web.UI.Control).UniqueID Is Nothing) Then
                            filterArray(total) = documentComponents(i)
                            total += 1
                        End If
                    End If
                Next i

                If total = 0 Then
                    Throw New Exception( _
                        "Document contains no System.Web.UI.Control components.")
                End If

                ' Move the components that derive from System.Web.UI.Control to a 
                ' new array of the correct size.
                Dim controlArray(total - 1) As System.Web.UI.Control

                For i = 0 To total - 1
                    controlArray(i) = CType(filterArray(i), System.Web.UI.Control)
                Next i

                ' Create a ControlSelectionForm to provide a persistence 
                ' configuration interface.
                Dim selectionForm As New ControlSelectionForm(controlArray)

                ' Display the form.
                If selectionForm.ShowDialog() <> DialogResult.OK Then
                    Return
                End If

                ' Validate the selection.
                If selectionForm.controlList.SelectedIndex = -1 Then
                    Throw New Exception("You must select a control to persist.")
                End If

                ' Parse the selected control.
                Dim persistedData As String = ControlPersister.PersistControl( _
                    controlArray(selectionForm.controlList.SelectedIndex))

                ' Display the control persistence string in a text box.
                Dim displayForm As New StringDisplayForm(persistedData)
                displayForm.ShowDialog()
            End Sub

            ' Displays a textbox form to receive an HTML 
            ' string that represents a control, and creates
            ' a toolbox item for the control, if not already
            ' present in the selected toolbox category.
            Private Sub loadPersistedControl()
                ' Display a StringInputForm to obtain a persisted control string.
                Dim inputForm As New StringInputForm()

                If inputForm.ShowDialog() <> DialogResult.OK Then
                    Return
                End If
                If inputForm.TxBox.Text.Length < 2 Then
                    Return
                End If
                ' Obtain an IDesignerHost for the design-mode document.
                Dim host As IDesignerHost = CType(Me.Component.Site.GetService(GetType(IDesignerHost)), IDesignerHost)

                ' Create a Web control from the persisted control string.
                Dim ctrl As System.Web.UI.Control = ControlParser.ParseControl(host, inputForm.TxBox.Text.Trim())

                ' Create a Web control toolbox item for the type of the control.
                Dim item As New System.Web.UI.Design.WebControlToolboxItem(ctrl.GetType())

                ' Add the Web control toolbox item to the toolbox.
                Dim toolService As IToolboxService = CType(Me.Component.Site.GetService(GetType(IToolboxService)), IToolboxService)
                If Not (toolService Is Nothing) Then
                    toolService.AddToolboxItem(item)
                Else
                    Throw New Exception("IToolboxService was not found.")
                End If
            End Sub
        End Class
    End Class

    ' Simple text display control hosts the ControlParserPersisterDesigner.
    <DesignerAttribute(GetType(ControlParserPersisterDesigner), _
        GetType(IDesigner))> _
    Public Class ControlParserPersisterDesignerControl
        Inherits System.Web.UI.WebControls.WebControl

        Private _text As String

        <Bindable(True), _
            Category("Appearance"), _
            DefaultValue("")> _
        Public Property [Text]() As String
            Get
                Return _text
            End Get
            Set(ByVal Value As String)
                _text = Value
            End Set
        End Property

        Public Sub New()
            [Text] = "Right-click here to access control persistence " & _
                        "methods in design mode"
        End Sub

        Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
            output.Write([Text])
        End Sub
    End Class

    ' Provides a form with a list for selection.
    Friend Class ControlSelectionForm
        Inherits System.Windows.Forms.Form
        Private controlArray() As System.Web.UI.Control
        Public controlList As System.Windows.Forms.ListBox

        Public Sub New(ByVal controlArray() As System.Web.UI.Control)
            Me.controlArray = controlArray

            Me.Size = New Size(400, 500)
            Me.Text = "Control Persister Selection Form"

            Me.SuspendLayout()

            Dim label1 As New System.Windows.Forms.Label()
            label1.Text = "Select the control to persist:"
            label1.Size = New Size(240, 20)
            label1.Location = New Point(10, 10)
            Me.Controls.Add(label1)

            controlList = New System.Windows.Forms.ListBox()
            controlList.Size = New Size(370, 400)
            controlList.Location = New Point(10, 30)
            controlList.Anchor = AnchorStyles.Left Or AnchorStyles.Top _
                    Or AnchorStyles.Bottom Or AnchorStyles.Right
            Me.Controls.Add(controlList)

            Dim okButton As New System.Windows.Forms.Button()
            okButton.Text = "OK"
            okButton.Size = New Size(80, 24)
            okButton.Location = New Point(Me.Width - 100, Me.Height - 60)
            okButton.Anchor = AnchorStyles.Bottom Or AnchorStyles.Right
            okButton.DialogResult = DialogResult.OK
            Me.Controls.Add(okButton)

            Dim cancelButton As New System.Windows.Forms.Button()
            cancelButton.Text = "Cancel"
            cancelButton.Size = New Size(80, 24)
            cancelButton.Location = New Point(Me.Width - 200, Me.Height - 60)
            cancelButton.Anchor = AnchorStyles.Bottom Or AnchorStyles.Right
            cancelButton.DialogResult = DialogResult.Cancel
            Me.Controls.Add(cancelButton)

            Dim i As Integer
            For i = 0 To controlArray.Length - 1
                controlList.Items.Add(controlArray(i).UniqueID)
            Next i
            Me.ResumeLayout()
        End Sub
    End Class

    ' Provides a form with a multiline text box display.
    Friend Class StringDisplayForm
        Inherits System.Windows.Forms.Form

        Private tbox As New System.Windows.Forms.TextBox()

        Public Property TxBox() As System.Windows.Forms.TextBox
            Get
                Return tbox
            End Get
            Set(ByVal value As System.Windows.Forms.TextBox)
                tbox = value
            End Set
        End Property

        Public Sub New(ByVal displayText As String)
            Me.Size = New Size(400, 300)
            Me.Text = "Control Persistence String"

            Me.SuspendLayout()
            Dim tbox As New System.Windows.Forms.TextBox()
            tbox.Multiline = True
            tbox.Size = New Size(Me.Width - 40, Me.Height - 90)
            tbox.Text = displayText
            Me.Controls.Add(tbox)

            Dim okButton As New System.Windows.Forms.Button()
            okButton.Text = "OK"
            okButton.Size = New Size(80, 24)
            okButton.Location = New Point(Me.Width - 100, Me.Height - 60)
            okButton.Anchor = AnchorStyles.Bottom Or AnchorStyles.Right
            okButton.DialogResult = DialogResult.OK
            Me.Controls.Add(okButton)

            Me.ResumeLayout()
        End Sub
    End Class

    ' Provides a form with a multiline text box for input.
    Friend Class StringInputForm
        Inherits System.Windows.Forms.Form
        Private tbox As New System.Windows.Forms.TextBox()

        Public Property TxBox() As System.Windows.Forms.TextBox
            Get
                Return tbox
            End Get
            Set(ByVal value As System.Windows.Forms.TextBox)
                tbox = value
            End Set
        End Property

        Public Sub New()
            Me.Size = New Size(400, 400)
            Me.Text = "Input Control Persistence String"

            Me.SuspendLayout()
            tbox = New System.Windows.Forms.TextBox()
            tbox.Multiline = True
            tbox.Size = New Size(Me.Width - 40, Me.Height - 90)
            tbox.Text = ""
            Me.Controls.Add(tbox)

            Dim okButton As New System.Windows.Forms.Button()
            okButton.Text = "OK"
            okButton.Size = New Size(80, 24)
            okButton.Location = New Point(Me.Width - 100, Me.Height - 60)
            okButton.Anchor = AnchorStyles.Bottom Or AnchorStyles.Right
            okButton.DialogResult = DialogResult.OK
            Me.Controls.Add(okButton)

            Dim cancelButton As New System.Windows.Forms.Button()
            cancelButton.Text = "Cancel"
            cancelButton.Size = New Size(80, 24)
            cancelButton.Location = New Point(Me.Width - 200, Me.Height - 60)
            cancelButton.Anchor = AnchorStyles.Bottom Or AnchorStyles.Right
            cancelButton.DialogResult = DialogResult.Cancel
            Me.Controls.Add(cancelButton)

            Me.ResumeLayout()
        End Sub
    End Class
End Namespace

Comentarios

La ControlPersister clase proporciona métodos que pueden conservar un Control control o una ITemplate implementación de interfaz como una cadena de código aspx. La implementación de estos métodos se controla mediante atributos de metadatos, como DefaultValueAttribute, PersistenceModeAttributey DesignerSerializationVisibilityAttribute.

Nota

El diseñador de páginas Web Forms no admite el Reset<em>PropertyName</em> método que, opcionalmente, expone Microsoft Windows Forms controles basados en la persistencia de propiedades.

Para crear un Control objeto o una ITemplate interfaz mediante el análisis de una cadena de datos de control o persistencia de plantillas, use los métodos de ControlParser clase .

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
PersistControl(Control)

Obtiene una cadena de datos que representa al formulario almacenado del control especificado.

PersistControl(Control, IDesignerHost)

Obtiene una cadena de datos que representa al formulario almacenado del control especificado, mediante el host del diseñador especificado.

PersistControl(TextWriter, Control)

Muestra una cadena de datos que representa al formulario almacenado del control especificado en el TextWriter especificado.

PersistControl(TextWriter, Control, IDesignerHost)

Proporciona una cadena de datos que representa al formulario almacenado del control especificado al TextWriter especificado mediante el host del diseñador especificado.

PersistInnerProperties(Object, IDesignerHost)

Obtiene una cadena de datos que puede almacenar las propiedades internas del control especificado.

PersistInnerProperties(TextWriter, Object, IDesignerHost)

Proporciona una cadena de datos en el TextWriter especificado, que puede almacenar las propiedades internas del control especificado mediante el host del diseñador especificado.

PersistTemplate(ITemplate, IDesignerHost)

Obtiene una cadena de datos que representa al formulario almacenado de la plantilla especificada.

PersistTemplate(TextWriter, ITemplate, IDesignerHost)

Escribe una cadena de datos que representa al formulario almacenado de la plantilla especificada en el objeto TextWriter especificado.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también