IDesignerHost Интерфейс

Определение

Предоставляет интерфейс для управления транзакциями и компонентами конструктора.

public interface class IDesignerHost : IServiceProvider, System::ComponentModel::Design::IServiceContainer
public interface class IDesignerHost : System::ComponentModel::Design::IServiceContainer
public interface IDesignerHost : IServiceProvider, System.ComponentModel.Design.IServiceContainer
[System.Runtime.InteropServices.ComVisible(true)]
public interface IDesignerHost : IServiceProvider, System.ComponentModel.Design.IServiceContainer
public interface IDesignerHost : System.ComponentModel.Design.IServiceContainer
type IDesignerHost = interface
    interface IServiceContainer
    interface IServiceProvider
[<System.Runtime.InteropServices.ComVisible(true)>]
type IDesignerHost = interface
    interface IServiceContainer
    interface IServiceProvider
Public Interface IDesignerHost
Implements IServiceContainer, IServiceProvider
Public Interface IDesignerHost
Implements IServiceContainer
Производный
Атрибуты
Реализации

Примеры

В следующем примере кода показано, как получить IDesignerHost интерфейс службы из конструктора или компонента сайта.

// Requests an IDesignerHost service from the design time environment using Component.Site.GetService()
IDesignerHost^ dh = static_cast<IDesignerHost^>(this->Component->Site->GetService( IDesignerHost::typeid ));
// Requests an IDesignerHost service from the design time environment using Component.Site.GetService()
IDesignerHost dh = (IDesignerHost) this.Component.Site.GetService(typeof(IDesignerHost));
' Requests an IDesignerHost service from the design time environment using Component.Site.GetService()
Dim host As IDesignerHost = CType(Me.Component.Site.GetService(GetType(IDesignerHost)), IDesignerHost)

В следующем примере кода показано использование IDesignerHost интерфейса для перечисления компонентов проекта.

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

using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::Security::Permissions;

// Provides a form containing a listbox that can display 
// a list of project components.
public ref class DesignerHostListForm: public System::Windows::Forms::Form
{
public:
   System::Windows::Forms::ListBox^ listBox1;

private:
   System::Windows::Forms::Button^ ok_button;

public:
   DesignerHostListForm()
   {
      this->Name = "DesignerHostListForm";
      this->Text = "List of design-time project components";
      this->SuspendLayout();
      this->listBox1 = gcnew System::Windows::Forms::ListBox;
      this->listBox1->Location = System::Drawing::Point( 8, 8 );
      this->listBox1->Name = "listBox1";
      this->listBox1->Size = System::Drawing::Size( 385, 238 );
      this->listBox1->TabIndex = 0;
      this->listBox1->Anchor = static_cast<AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right);
      this->ok_button = gcnew System::Windows::Forms::Button;
      this->ok_button->DialogResult = System::Windows::Forms::DialogResult::OK;
      this->ok_button->Location = System::Drawing::Point( 232, 256 );
      this->ok_button->Name = "ok_button";
      this->ok_button->TabIndex = 1;
      this->ok_button->Text = "OK";
      this->ok_button->Anchor = static_cast<AnchorStyles>(System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right);
      this->ClientSize = System::Drawing::Size( 400, 285 );
      array<System::Windows::Forms::Control^>^temp2 = {this->ok_button,this->listBox1};
      this->Controls->AddRange( temp2 );
      this->ResumeLayout( false );
   }

public:
   ~DesignerHostListForm()
   {
   }
};


// You can double-click the component of an IDesignerHostExampleDesigner 
// to show a form containing a listbox that lists the name and type 
// of each component or control in the current design-time project.
public ref class IDesignerHostExampleDesigner: public IDesigner
{
private:
   System::ComponentModel::IComponent^ component;

public:
   IDesignerHostExampleDesigner(){}

   virtual void DoDefaultAction()
   {
      ListComponents();
   }

   virtual void Initialize( System::ComponentModel::IComponent^ component )
   {
      this->component = component;
      MessageBox::Show( "Double-click the IDesignerHostExample component to view a list of project components." );
   }


private:

   // Displays a list of components in the current design 
   // document when the default action of the designer is invoked.
   void ListComponents()
   {
      DesignerHostListForm^ listform = gcnew DesignerHostListForm;

      // Obtain an IDesignerHost service from the design environment.
      IDesignerHost^ host = dynamic_cast<IDesignerHost^>(this->component->Site->GetService( IDesignerHost::typeid ));

      // Get the project components container (control containment depends on Controls collections)
      IContainer^ container = host->Container;

      // Add each component's type name and name to the list box.
      System::Collections::IEnumerator^ myEnum = container->Components->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         IComponent^ component = safe_cast<IComponent^>(myEnum->Current);
         listform->listBox1->Items->Add( String::Concat( component->GetType()->Name, " : ", component->Site->Name ) );
      }

      listform->ShowDialog();
   }

public:

   property System::ComponentModel::IComponent^ Component 
   {
      virtual System::ComponentModel::IComponent^ get()
      {
         return this->component;
      }
   }

   property System::ComponentModel::Design::DesignerVerbCollection^ Verbs 
   {
      [PermissionSetAttribute(SecurityAction::Demand, Name="FullTrust")]
      virtual System::ComponentModel::Design::DesignerVerbCollection^ get()
      {
         DesignerVerbCollection^ dvc = gcnew DesignerVerbCollection;
         dvc->Add( gcnew DesignerVerb( "List Components",gcnew EventHandler( this, &IDesignerHostExampleDesigner::ListHandler ) ) );
         return dvc;
      }
   }

private:
   void ListHandler( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      ListComponents();
   }

public:
   ~IDesignerHostExampleDesigner(){}
};


// IDesignerHostExampleComponent is a component associated 
// with the IDesignerHostExampleDesigner that demonstrates 
// acquisition and use of the IDesignerHost service 
// to list project components.

[DesignerAttribute(IDesignerHostExampleDesigner::typeid)]
public ref class IDesignerHostExampleComponent: public System::ComponentModel::Component
{
public:
   IDesignerHostExampleComponent(){}

public:
   ~IDesignerHostExampleComponent(){}
};
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;

namespace IDesignerHostExample
{	
    // IDesignerHostExampleComponent is a component associated 
    // with the IDesignerHostExampleDesigner that demonstrates 
    // acquisition and use of the IDesignerHost service 
    // to list project components.
    [DesignerAttribute(typeof(IDesignerHostExampleDesigner))]
    public class IDesignerHostExampleComponent : System.ComponentModel.Component
    {
        public IDesignerHostExampleComponent()
        {}

        protected override void Dispose( bool disposing )
        {
            base.Dispose( disposing );
        }
    }

    // You can double-click the component of an IDesignerHostExampleDesigner 
    // to show a form containing a listbox that lists the name and type 
    // of each component or control in the current design-time project.
    public class IDesignerHostExampleDesigner : IDesigner
    {
        private System.ComponentModel.IComponent component;

        public IDesignerHostExampleDesigner()
        {}

        public void DoDefaultAction()
        {
            ListComponents();
        }

        public void Initialize(System.ComponentModel.IComponent component)
        {
            this.component = component;
            MessageBox.Show("Double-click the IDesignerHostExample component to view a list of project components.");
        }

        // Displays a list of components in the current design 
        // document when the default action of the designer is invoked.
        private void ListComponents()
        {
            using (DesignerHostListForm listform = new DesignerHostListForm())
            {
                // Obtain an IDesignerHost service from the design environment.
                IDesignerHost host = (IDesignerHost)this.component.Site.GetService(typeof(IDesignerHost));
                // Get the project components container (control containment depends on Controls collections)
                IContainer container = host.Container;
                // Add each component's type name and name to the list box.
                foreach (IComponent component in container.Components)
                {
                    listform.listBox1.Items.Add(component.GetType().Name + " : " + component.Site.Name);
                }
                // Display the form.
                listform.ShowDialog();
            }
        }

        public System.ComponentModel.IComponent Component
        {
            get
            {
                return this.component;
            }
        }

        public System.ComponentModel.Design.DesignerVerbCollection Verbs
        {
            get
            {
                DesignerVerbCollection dvc = new DesignerVerbCollection();
                dvc.Add( new DesignerVerb("List Components", new EventHandler(ListHandler)) );
                return dvc;
            }
        }

        private void ListHandler(object sender, EventArgs e)
        {
            ListComponents();
        }

        public void Dispose() {	}
    }

    // Provides a form containing a listbox that can display 
    // a list of project components.
    public class DesignerHostListForm : System.Windows.Forms.Form
    {
        public System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.Button ok_button;
        
        public DesignerHostListForm()
        {
            this.Name = "DesignerHostListForm";
            this.Text = "List of design-time project components";
            this.SuspendLayout();
            this.listBox1 = new System.Windows.Forms.ListBox();						
            this.listBox1.Location = new System.Drawing.Point(8, 8);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(385, 238);
            this.listBox1.TabIndex = 0;	
            this.listBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);		
            this.ok_button = new System.Windows.Forms.Button();
            this.ok_button.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.ok_button.Location = new System.Drawing.Point(232, 256);
            this.ok_button.Name = "ok_button";
            this.ok_button.TabIndex = 1;
            this.ok_button.Text = "OK";
            this.ok_button.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
            this.ClientSize = new System.Drawing.Size(400, 285);
            this.Controls.AddRange(new System.Windows.Forms.Control[] { this.ok_button, this.listBox1 });
            this.ResumeLayout(false);	
        }

        protected override void Dispose( bool disposing )
        {			
            base.Dispose( disposing );
        }	
    }
}
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing
Imports System.Windows.Forms

Namespace IDesignerHostExample
   
   ' IDesignerHostExampleComponent is a component associated 
   ' with the IDesignerHostExampleDesigner that demonstrates 
   ' acquisition and use of the IDesignerHost service 
   ' to list project components.
    <DesignerAttribute(GetType(IDesignerHostExampleDesigner))> _
    Public Class IDesignerHostExampleComponent
        Inherits System.ComponentModel.Component

        Public Sub New()
        End Sub

        Protected Overloads Sub Dispose(ByVal disposing As Boolean)
            MyBase.Dispose(disposing)
        End Sub 
    End Class 

    ' You can double-click the component of a IDesignerHostExampleDesigner
    ' to show a form containing a listbox that lists the name and type 
    ' of each component or control in the current design-time project.
    <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
    Public Class IDesignerHostExampleDesigner
        Implements IDesigner
        Private component_ As System.ComponentModel.IComponent

        Public Sub New()
        End Sub

        Public Sub DoDefaultAction() Implements IDesigner.DoDefaultAction
            ListComponents()
        End Sub

        Public Sub Initialize(ByVal component As System.ComponentModel.IComponent) Implements IDesigner.Initialize
            Me.component_ = component
            MessageBox.Show("Double-click the IDesignerHostExample component to view a list of project components.")
        End Sub

        ' Displays a list of components in the current design 
        ' document when the default action of the designer is invoked.
        Private Sub ListComponents()

            Using listform As New DesignerHostListForm()

                ' Obtain an IDesignerHost service from the design environment.
                Dim host As IDesignerHost = CType(Me.Component.Site.GetService(GetType(IDesignerHost)), IDesignerHost)
                ' Get the project components container (control containment depends on Controls collections)
                Dim container As IContainer = host.Container
                ' Add each component's type name and name to the list box.
                Dim comp As Component
                For Each comp In container.Components
                    listform.listBox1.Items.Add((comp.GetType().Name + " : " + Component.Site.Name))
                Next comp
                ' Display the form.
                listform.ShowDialog()

            End Using

        End Sub

        Public ReadOnly Property Component() As System.ComponentModel.IComponent Implements IDesigner.Component
            Get
                Return component_
            End Get
        End Property

        Public ReadOnly Property Verbs() As System.ComponentModel.Design.DesignerVerbCollection Implements IDesigner.Verbs
            Get
                Dim dvc As New DesignerVerbCollection()
                dvc.Add(New DesignerVerb("List Components", New EventHandler(AddressOf ListHandler)))
                Return dvc
            End Get
        End Property

        Private Sub ListHandler(ByVal sender As Object, ByVal e As EventArgs)
            ListComponents()
        End Sub

        Public Sub Dispose() Implements IDisposable.Dispose
        End Sub
    End Class
    _ 

    ' Provides a form containing a list box that can display 
    ' a list of project components.
    Public Class DesignerHostListForm
        Inherits System.Windows.Forms.Form
        Public listBox1 As System.Windows.Forms.ListBox
        Private ok_button As System.Windows.Forms.Button

        Public Sub New()
            Me.Name = "DesignerHostListForm"
            Me.Text = "List of design-time project components"
            Me.SuspendLayout()
            Me.listBox1 = New System.Windows.Forms.ListBox()
            Me.listBox1.Location = New System.Drawing.Point(8, 8)
            Me.listBox1.Name = "listBox1"
            Me.listBox1.Size = New System.Drawing.Size(385, 238)
            Me.listBox1.TabIndex = 0
            Me.listBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
            Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right)
            Me.ok_button = New System.Windows.Forms.Button()
            Me.ok_button.DialogResult = System.Windows.Forms.DialogResult.OK
            Me.ok_button.Location = New System.Drawing.Point(232, 256)
            Me.ok_button.Name = "ok_button"
            Me.ok_button.TabIndex = 1
            Me.ok_button.Text = "OK"
            Me.ok_button.Anchor = (System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right)
            Me.ClientSize = New System.Drawing.Size(400, 285)
            Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.ok_button, Me.listBox1})
            Me.ResumeLayout(False)
        End Sub 

        Protected Overloads Sub Dispose(ByVal disposing As Boolean)
            MyBase.Dispose(disposing)
        End Sub 
    End Class 
End Namespace

Комментарии

IDesignerHost — это интерфейс, который работает с архитектурой конструктора форм .NET Framework для обеспечения поддержки управления транзакциями и компонентами конструктора.

Платформа .NET не предоставляет реализацию этого интерфейса. Интерфейс реализуется средствами разработки, поддерживающими конструкторы.

Примечания для тех, кто вызывает этот метод

Чтобы получить реализацию из среды разработки IDesignerHost , вызовите GetService(Type) , пока компонент активен в режиме разработки, передав тип IDesignerHost запроса IDesignerHost интерфейса службы.

IDesignerHost предоставляет следующие члены, связанные с состоянием конструктора:

  • Свойство Loading указывает, загружается ли конструктор или документ.

  • Событие Activated возникает при активации конструктора перед отображением.

  • Событие Deactivated возникает при деактивации конструктора.

  • Событие LoadComplete происходит после загрузки документа.

  • Метод Activate() активирует конструктор.

IDesignerHost предоставляет следующие члены, связанные с управлением компонентами:

  • Свойство Container указывает контейнер для узла конструктора.

  • Свойство RootComponent указывает базовый класс для корневого компонента.

  • Свойство RootComponentClassName указывает имя класса корневого компонента.

  • Метод CreateComponent(Type) создает указанный тип компонента.

  • Метод DestroyComponent(IComponent) уничтожает указанный компонент.

  • Метод GetDesigner(IComponent) получает конструктор, связанный с указанным компонентом.

  • Метод GetType(String) получает экземпляр типа с указанным именем.

IDesignerHost предоставляет следующие члены, связанные с управлением транзакциями:

  • Свойство InTransaction указывает, находится ли конструктор в транзакции.

  • Свойство указывает текущее TransactionDescription описание транзакции.

  • Событие TransactionClosed возникает при завершении транзакции.

  • Событие TransactionClosing возникает, когда транзакция будет завершена.

  • Событие TransactionOpened возникает при запуске транзакции.

  • Событие TransactionOpening возникает, когда транзакция начинается.

  • Метод CreateTransaction() создает и возвращает новую транзакцию.

Свойства

Имя Описание
Container

Возвращает контейнер для этого узла конструктора.

InTransaction

Возвращает значение, указывающее, находится ли узел конструктора в текущей транзакции.

Loading

Возвращает значение, указывающее, загружает ли узел конструктора документ.

RootComponent

Возвращает экземпляр базового класса, используемого в качестве корневого компонента для текущей структуры.

RootComponentClassName

Возвращает полное имя создаваемого класса.

TransactionDescription

Возвращает описание текущей транзакции.

Методы

Имя Описание
Activate()

Активирует конструктор, на котором размещен этот узел.

AddService(Type, Object, Boolean)

Добавляет указанную службу в контейнер службы и при необходимости повышает уровень службы к любым родительским контейнерам служб.

(Унаследовано от IServiceContainer)
AddService(Type, Object)

Добавляет указанную службу в контейнер службы.

(Унаследовано от IServiceContainer)
AddService(Type, ServiceCreatorCallback, Boolean)

Добавляет указанную службу в контейнер службы и при необходимости повышает уровень службы в родительские контейнеры служб.

(Унаследовано от IServiceContainer)
AddService(Type, ServiceCreatorCallback)

Добавляет указанную службу в контейнер службы.

(Унаследовано от IServiceContainer)
CreateComponent(Type, String)

Создает компонент указанного типа и имени и добавляет его в документ конструктора.

CreateComponent(Type)

Создает компонент указанного типа и добавляет его в документ конструктора.

CreateTransaction()

DesignerTransaction Создает инкапсулировать последовательности событий, чтобы повысить производительность и включить функциональность отмены и повторного выполнения.

CreateTransaction(String)

DesignerTransaction Создает инкапсулировать последовательности событий для повышения производительности и включения функций поддержки отмены и повторного выполнения, используя указанное описание транзакции.

DestroyComponent(IComponent)

Удаляет указанный компонент и удаляет его из контейнера конструктора.

GetDesigner(IComponent)

Возвращает экземпляр конструктора, содержащий указанный компонент.

GetService(Type)

Возвращает объект службы указанного типа.

(Унаследовано от IServiceProvider)
GetType(String)

Возвращает экземпляр указанного полного имени типа.

RemoveService(Type, Boolean)

Удаляет указанный тип службы из контейнера службы и при необходимости повышает уровень службы в родительские контейнеры служб.

(Унаследовано от IServiceContainer)
RemoveService(Type)

Удаляет указанный тип службы из контейнера службы.

(Унаследовано от IServiceContainer)

События

Имя Описание
Activated

Происходит при активации этого конструктора.

Deactivated

Происходит при деактивации этого конструктора.

LoadComplete

Происходит, когда этот конструктор завершает загрузку документа.

TransactionClosed

Добавляет обработчик событий для TransactionClosed события.

TransactionClosing

Добавляет обработчик событий для TransactionClosing события.

TransactionOpened

Добавляет обработчик событий для TransactionOpened события.

TransactionOpening

Добавляет обработчик событий для TransactionOpening события.

Методы расширения

Имя Описание
CreateAsyncScope(IServiceProvider)

Создает новый AsyncServiceScope объект, который можно использовать для разрешения служб с областью действия.

CreateScope(IServiceProvider)

Создает новый IServiceScope объект, который можно использовать для разрешения служб с областью действия.

GetKeyedService(IServiceProvider, Type, Object)

Получение службы типа serviceType из .IServiceProvider

GetKeyedService<T>(IServiceProvider, Object)

Получение службы типа T из .IServiceProvider

GetKeyedServices(IServiceProvider, Type, Object)

Получение перечисления служб типа serviceType из .IServiceProvider

GetKeyedServices<T>(IServiceProvider, Object)

Получение перечисления служб типа T из .IServiceProvider

GetRequiredKeyedService(IServiceProvider, Type, Object)

Получение службы типа serviceType из .IServiceProvider

GetRequiredKeyedService<T>(IServiceProvider, Object)

Получение службы типа T из .IServiceProvider

GetRequiredService(IServiceProvider, Type)

Получение службы типа serviceType из .IServiceProvider

GetRequiredService<T>(IServiceProvider)

Получение службы типа T из .IServiceProvider

GetService<T>(IServiceProvider)

Получение службы типа T из .IServiceProvider

GetServices(IServiceProvider, Type)

Получение перечисления служб типа serviceType из .IServiceProvider

GetServices<T>(IServiceProvider)

Получение перечисления служб типа T из .IServiceProvider

Применяется к

См. также раздел