DesignerTransaction DesignerTransaction DesignerTransaction DesignerTransaction Class

Definición

Permite agrupar una serie de acciones en tiempo de diseño para mejorar el rendimiento y habilitar la posibilidad de deshacer la mayoría de los tipos de cambio.Provides a way to group a series of design-time actions to improve performance and enable most types of changes to be undone.

public ref class DesignerTransaction abstract : IDisposable
public abstract class DesignerTransaction : IDisposable
type DesignerTransaction = class
    interface IDisposable
Public MustInherit Class DesignerTransaction
Implements IDisposable
Herencia
DesignerTransactionDesignerTransactionDesignerTransactionDesignerTransaction
Implementaciones

Ejemplos

En el siguiente programa de ejemplo de código se muestra DesignerTransaction cómo crear un desde un diseñador.The following code example program demonstrates how to create a DesignerTransaction from a designer. Para ejecutar este ejemplo, compile el código fuente en una biblioteca de clases.To run this sample, compile the source code into a class library. Debe agregar una referencia al ensamblado System. Design.You must add a reference to the System.Design assembly. En un nuevo proyecto, agregue una referencia al archivo DLL compilado y agregue el componente de la biblioteca al cuadro de herramientas.In a new project, add a reference to the compiled DLL and add the component in the library to the Toolbox.

Hay una amplia compatibilidad para esta característica en Visual Studio.There is extensive support for this feature in Visual Studio.

Consulte también Tutorial: Rellenar automáticamente el cuadro deherramientas con componentes personalizados.Also see Walkthrough: Automatically Populating the Toolbox with Custom Components.

Opcionalmente, el diseñador puede mostrar notificaciones sobre eventos de transacción del diseñador.The designer can optionally display notifications about designer transaction events. Si agrega una instancia de DTComponent a un formulario en modo de diseño, aparecerá un cuadro de mensaje en el que se le preguntará si desea recibir notificaciones de eventos de transacción del diseñador.If you add an instance of the DTComponent to a form while in design mode, a message box appears asking whether you would like to receive designer transaction event notifications. Puede alternar estas notificaciones mediante el menú contextual que aparece cuando hace clic con el botón secundario en una DTComponentinstancia de.You may toggle these notifications using the shortcut menu that appears when you right-click an instance of the DTComponent. Las transacciones se crean al cambiar los valores mediante el ventana Propiedades.Transactions are created when you change values using the Properties window. También puede hacer que el diseñador realice una transacción haciendo clic en realizar transacción de ejemplo en el menú contextual del componente.You can also have the designer perform a transaction by clicking Perform Example Transaction on the shortcut menu for the component.

#using <system.dll>
#using <system.design.dll>
#using <system.windows.forms.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Windows::Forms;
using namespace System::Windows::Forms::Design;

/*
This sample demonstrates how to perform a series of actions in a designer
transaction, how to change values of properties of a component from a
designer, and how to complete transactions without being interrupted
by other activities.

To run this sample, add this code to a class library project and compile.
Create a new Windows Forms project or load a form in the designer. Add a
reference to the class library that was compiled in the first step.
Right-click the Toolbox in design mode and click Customize Toolbox.
Browse to the class library that was compiled in the first step and
select OK until the DTComponent item appears in the Toolbox.  Add an
instance of this component to the form.

When the component is created and added to the component tray for your
design project, the Initialize method of the designer is called.
This method displays a message box informing you that designer transaction
event handlers will be registered unless you click Cancel. When you set
properties in the properties window, each change will be encapsulated in
a designer transaction, allowing the change to be undone later.

When you right-click the component, the shortcut menu for the component
is displayed. The designer constructs this menu according to whether
designer transaction notifications are enabled, and offers the option
of enabling or disabling the notifications, depending on the current
mode. The shortcut menu also presents a Perform Example Transaction
item, which will set the values of the component's StringProperty and
CountProperty properties. You can undo the last designer transaction using
the Undo command provided by the Visual Studio development environment.
*/

private ref class DTDesigner: public ComponentDesigner
{
private:
   bool notification_mode;
   int count;
   void LinkDTNotifications( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      if (  !notification_mode )
      {
         IDesignerHost^ host = dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid ));
         if ( host != nullptr )
         {
            notification_mode = true;
            host->TransactionOpened += gcnew EventHandler( this, &DTDesigner::OnDesignerTransactionOpened );
            host->TransactionClosed += gcnew DesignerTransactionCloseEventHandler( this, &DTDesigner::OnDesignerTransactionClosed );
         }
      }
   }

   void UnlinkDTNotifications( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      if ( notification_mode )
      {
         IDesignerHost^ host = dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid ));
         if ( host != nullptr )
         {
            notification_mode = false;
            host->TransactionOpened -= gcnew EventHandler( this, &DTDesigner::OnDesignerTransactionOpened );
            host->TransactionClosed -= gcnew DesignerTransactionCloseEventHandler( this, &DTDesigner::OnDesignerTransactionClosed );
         }
      }
   }

   void OnDesignerTransactionOpened( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      MessageBox::Show( "A Designer Transaction was started. (TransactionOpened)" );
   }

   void OnDesignerTransactionClosed( Object^ /*sender*/, DesignerTransactionCloseEventArgs^ /*e*/ )
   {
      MessageBox::Show( "A Designer Transaction was completed. (TransactionClosed)" );
   }

   void DoTransaction( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      IDesignerHost^ host = static_cast<IDesignerHost^>(GetService( IDesignerHost::typeid ));
      DesignerTransaction^ t = host->CreateTransaction( "Change Text and Size" );
      
      /* The code within the using statement is considered to be a single transaction.
              When the user selects Undo, the system will undo everything executed in this code block.
              */
      if ( notification_mode )
            MessageBox::Show( "Entering a Designer-Initiated Designer Transaction" );

      // The .NET Framework automatically associates the TypeDescriptor with the correct component
      PropertyDescriptor^ someText = TypeDescriptor::GetProperties( Component )[ "StringProperty" ];
      someText->SetValue( Component, "This text was set by the designer for this component." );
      PropertyDescriptor^ anInteger = TypeDescriptor::GetProperties( Component )[ "CountProperty" ];
      anInteger->SetValue( Component, count );
      count++;

      // Complete the designer transaction.
      t->Commit();
      if ( notification_mode )
            MessageBox::Show( "Designer-Initiated Designer Transaction Completed" );
   }

public:
   property DesignerVerbCollection^ Verbs 
   {
      // The Verbs property is overridden from ComponentDesigner
      virtual DesignerVerbCollection^ get() override
      {
         DesignerVerbCollection^ dvc = gcnew DesignerVerbCollection;
         dvc->Add( gcnew DesignerVerb( "Perform Example Transaction",gcnew EventHandler( this, &DTDesigner::DoTransaction ) ) );
         if ( notification_mode )
                  dvc->Add( gcnew DesignerVerb( "End Designer Transaction Notifications",
                     gcnew EventHandler( this, &DTDesigner::UnlinkDTNotifications ) ) );
         else
                  dvc->Add( gcnew DesignerVerb( "Show Designer Transaction Notifications",
                     gcnew EventHandler( this, &DTDesigner::LinkDTNotifications ) ) );

         return dvc;
      }
   }
   virtual void Initialize( IComponent^ component ) override
   {
      ComponentDesigner::Initialize( component );
      notification_mode = false;
      count = 10;
      IDesignerHost^ host = dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid ));
      if ( host == nullptr )
      {
         MessageBox::Show( "The IDesignerHost service interface could not be obtained." );
         return;
      }

      if ( MessageBox::Show( "Press the Yes button to display notification message boxes for the designer transaction opened and closed notifications.", "Link DesignerTransaction Notifications?", MessageBoxButtons::YesNo, MessageBoxIcon::Question, MessageBoxDefaultButton::Button1, MessageBoxOptions::RightAlign ) == DialogResult::Yes )
      {
         host->TransactionOpened += gcnew EventHandler( this, &DTDesigner::OnDesignerTransactionOpened );
         host->TransactionClosed += gcnew DesignerTransactionCloseEventHandler( this, &DTDesigner::OnDesignerTransactionClosed );
         notification_mode = true;
      }
   }

public:
   ~DTDesigner()
   {
      UnlinkDTNotifications( this, gcnew EventArgs );
   }
};

// Associate the DTDesigner with this component

[DesignerAttribute(DTDesigner::typeid)]
public ref class DTComponent: public System::ComponentModel::Component
{
private:
   String^ m_String;
   int m_Count;
   void InitializeComponent()
   {
      m_String = "Initial Value";
      m_Count = 0;
   }

public:
   property String^ StringProperty 
   {
      String^ get()
      {
         return m_String;
      }

      void set( String^ value )
      {
         m_String = value;
      }
   }

   property int CountProperty 
   {
      int get()
      {
         return m_Count;
      }

      void set( int value )
      {
         m_Count = value;
      }
   }
};
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;

/*
    This sample demonstrates how to perform a series of actions in a designer 
    transaction, how to change values of properties of a component from a 
    designer, and how to complete transactions without being interrupted 
    by other activities.

    To run this sample, add this code to a class library project and compile. 
    Create a new Windows Forms project or load a form in the designer. Add a 
    reference to the class library that was compiled in the first step.
    Right-click the Toolbox in design mode and click Customize Toolbox.  
    Browse to the class library that was compiled in the first step and 
    select OK until the DTComponent item appears in the Toolbox.  Add an 
    instance of this component to the form.  
    
    When the component is created and added to the component tray for your
    design project, the Initialize method of the designer is called. 
    This method displays a message box informing you that designer transaction
    event handlers will be registered unless you click Cancel. When you set 
    properties in the properties window, each change will be encapsulated in 
    a designer transaction, allowing the change to be undone later.  
    
    When you right-click the component,	the shortcut menu for the component 
    is displayed. The designer constructs this menu according to whether 
    designer transaction notifications are enabled, and offers the option
    of enabling or disabling the notifications, depending on the current 
    mode. The shortcut menu also presents a Perform Example Transaction 
    item, which will set the values of the component's StringProperty and 
    CountProperty properties. You can undo the last designer transaction using 
    the Undo command provided by the Visual Studio development environment.
*/

namespace DesignerTransactionSample
{
    // Associate the DTDesigner with this component
    [DesignerAttribute(typeof(DTDesigner))]
    public class DTComponent : System.ComponentModel.Component
    {
        private string m_String;
    private int m_Count;
            
    public string StringProperty
    {
        get
            { return m_String; }
        set
        { m_String = value; }
    }
            
    public int CountProperty
    {
        get
        { return m_Count; }
        set
        { m_Count = value; }
    }

    private void InitializeComponent()
    {
        m_String = "Initial Value";
        m_Count = 0;
    }
    }
    
    internal class DTDesigner : ComponentDesigner
    {
    private bool notification_mode = false;
    private int count = 10;
        
    // The Verbs property is overridden from ComponentDesigner
    public override DesignerVerbCollection Verbs
    {
        get
        {				
            DesignerVerbCollection dvc = new DesignerVerbCollection();				
        dvc.Add( new DesignerVerb("Perform Example Transaction", new EventHandler(this.DoTransaction)) );
        if(notification_mode)
            dvc.Add(new DesignerVerb("End Designer Transaction Notifications", new EventHandler(this.UnlinkDTNotifications)));
        else
            dvc.Add(new DesignerVerb("Show Designer Transaction Notifications", new EventHandler(this.LinkDTNotifications)));				return dvc;
        }
    }
        
        public override void Initialize(System.ComponentModel.IComponent component)
        {
            base.Initialize(component);

            IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));			
            if(host == null)
            {
                MessageBox.Show("The IDesignerHost service interface could not be obtained.");
                return;
            }

            if( MessageBox.Show("Press the Yes button to display notification message boxes for the designer transaction opened and closed notifications.","Link DesignerTransaction Notifications?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign) == DialogResult.Yes )
            {							
            host.TransactionOpened += new EventHandler(OnDesignerTransactionOpened);
                host.TransactionClosed += new DesignerTransactionCloseEventHandler(OnDesignerTransactionClosed);
                notification_mode = true;
            }
        }
        
        private void LinkDTNotifications(object sender, EventArgs e)
        {
            if(notification_mode == false)
            {
            IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));							
                if(host != null)
            {
            notification_mode = true;
                   host.TransactionOpened += new EventHandler(OnDesignerTransactionOpened);
                   host.TransactionClosed += new DesignerTransactionCloseEventHandler(OnDesignerTransactionClosed);
            }
        }
        }

        private void UnlinkDTNotifications(object sender, EventArgs e)
        {
        if(notification_mode)
            {
                IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));							
            if(host != null)
                {				
            notification_mode = false;
                    host.TransactionOpened -= new EventHandler(OnDesignerTransactionOpened);
                    host.TransactionClosed -= new DesignerTransactionCloseEventHandler(OnDesignerTransactionClosed);
                }
            }
        }

        private void OnDesignerTransactionOpened(object sender, EventArgs e)
        {			
        System.Windows.Forms.MessageBox.Show("A Designer Transaction was started. (TransactionOpened)");
        }

        private void OnDesignerTransactionClosed(object sender, DesignerTransactionCloseEventArgs e)
        {			
        System.Windows.Forms.MessageBox.Show("A Designer Transaction was completed. (TransactionClosed)");
        }   

        private void DoTransaction(object sender, EventArgs e) 
        {			
            IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));			
            DesignerTransaction t = host.CreateTransaction("Change Text and Size");

            /* The code within the using statement is considered to be a single transaction.
           When the user selects Undo, the system will undo everything executed in this code block. */
            using (t)
            {
            if(notification_mode)
                System.Windows.Forms.MessageBox.Show("Entering a Designer-Initiated Designer Transaction");
                
                // The .NET Framework automatically associates the TypeDescriptor with the correct component
            PropertyDescriptor someText = TypeDescriptor.GetProperties(Component)["StringProperty"];
                someText.SetValue(Component, "This text was set by the designer for this component.");

                PropertyDescriptor anInteger = TypeDescriptor.GetProperties(Component)["CountProperty"];
            anInteger.SetValue(Component, count);
            count++;

                // Complete the designer transaction.
            t.Commit();
                
            if(notification_mode)
                System.Windows.Forms.MessageBox.Show("Designer-Initiated Designer Transaction Completed");
            }
        }
        
    protected override void Dispose(bool disposing)
    {
        UnlinkDTNotifications(this, new EventArgs());
        base.Dispose(disposing);
    }
    }
}
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Windows.Forms
Imports System.Windows.Forms.Design

'   This sample demonstrates how to perform a series of actions in a designer 
'   transaction, how to change values of properties of a component from a 
'   designer, and how to complete transactions without being interrupted 
'   by other activities.

'   To run this sample, add this code to a class library project and compile. 
'   Create a new Windows Forms project or load a form in the designer. Add a 
'   reference to the class library that was compiled in the first step.
'   Right-click the Toolbox in design mode and click Customize Toolbox.  
'   Browse to the class library that was compiled in the first step and 
'   select OK until the DTComponent item appears in the Toolbox.  Add an 
'   instance of this component to the form.  

'   When the component is created and added to the component tray for your
'   design project, the Initialize method of the designer is called. 
'   This method displays a message box informing you that designer transaction
'   event handlers are being registered unless you click Cancel. When you set 
'   properties in the properties window, each change will be encapsulated in 
'   a designer transaction, allowing the change to be undone later.  

'   When you right-click the component, the shortcut menu for the component 
'   is displayed. The designer constructs this menu according to whether 
'   designer transaction notifications are enabled, and offers the option
'   of enabling or disabling the notifications, depending on the current 
'   mode. The shortcut menu also presents a Perform Example Transaction 
'   item which will set the values of the component's StringProperty and 
'   CountProperty properties. You can undo the last designer transaction using 
'   the Undo command provided by the Visual Studio development environment.	

Namespace DesignerTransactionSample

    ' Associate the DTDesigner with this component
    <DesignerAttribute(GetType(DTDesigner))> _
    Public Class DTComponent
        Inherits System.ComponentModel.Component
        Private m_String As String
        Private m_Count As Integer

        Public Property StringProperty() As String
            Get
                Return m_String
            End Get
            Set(ByVal Value As String)
                m_String = Value
            End Set
        End Property

        Public Property CountProperty() As Integer
            Get
                Return m_Count
            End Get
            Set(ByVal Value As Integer)
                m_Count = Value
            End Set
        End Property

        Private Sub InitializeComponent()
            m_String = "Initial Value"
            m_Count = 0
        End Sub

    End Class

    Friend Class DTDesigner
        Inherits ComponentDesigner

        Private notification_mode As Boolean = False
        Private count As Integer = 10

        ' The Verbs property is overridden from ComponentDesigner
        Public Overrides ReadOnly Property Verbs() As DesignerVerbCollection
            Get
                Dim dvc As New DesignerVerbCollection()
                dvc.Add(New DesignerVerb("Perform Example Transaction", AddressOf Me.DoTransaction))
                If notification_mode Then
                    dvc.Add(New DesignerVerb("End Designer Transaction Notifications", AddressOf Me.UnlinkDTNotifications))
                Else
                    dvc.Add(New DesignerVerb("Show Designer Transaction Notifications", AddressOf Me.LinkDTNotifications))
                End If
                Return dvc
            End Get
        End Property

        Public Overrides Sub Initialize(ByVal component As System.ComponentModel.IComponent)
            MyBase.Initialize(component)

            Dim host As IDesignerHost = CType(GetService(GetType(IDesignerHost)), IDesignerHost)
            If host Is Nothing Then
                MessageBox.Show("The IDesignerHost service interface could not be obtained.")
                Return
            End If

            If MessageBox.Show("Press the Yes button to display notification message boxes for the designer transaction opened and closed notifications.", "Link DesignerTransaction Notifications?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign) = DialogResult.Yes Then
                AddHandler host.TransactionOpened, AddressOf OnDesignerTransactionOpened
                AddHandler host.TransactionClosed, AddressOf OnDesignerTransactionClosed
                notification_mode = True
            End If
        End Sub

        Private Sub LinkDTNotifications(ByVal sender As Object, ByVal e As EventArgs)
            If notification_mode = False Then
                Dim host As IDesignerHost = CType(GetService(GetType(IDesignerHost)), IDesignerHost)
                If (host IsNot Nothing) Then
                    notification_mode = True
                    AddHandler host.TransactionOpened, AddressOf OnDesignerTransactionOpened
                    AddHandler host.TransactionClosed, AddressOf OnDesignerTransactionClosed
                End If
            End If
        End Sub

        Private Sub UnlinkDTNotifications(ByVal sender As Object, ByVal e As EventArgs)
            If notification_mode Then
                Dim host As IDesignerHost = CType(GetService(GetType(IDesignerHost)), IDesignerHost)
                If (host IsNot Nothing) Then
                    notification_mode = False
                    RemoveHandler host.TransactionOpened, AddressOf Me.OnDesignerTransactionOpened
                    RemoveHandler host.TransactionClosed, AddressOf Me.OnDesignerTransactionClosed
                End If
            End If
        End Sub

        Private Sub OnDesignerTransactionOpened(ByVal sender As Object, ByVal e As EventArgs)
            System.Windows.Forms.MessageBox.Show("A Designer Transaction was started. (TransactionOpened)")
        End Sub

        Private Sub OnDesignerTransactionClosed(ByVal sender As Object, ByVal e As DesignerTransactionCloseEventArgs)
            System.Windows.Forms.MessageBox.Show("A Designer Transaction was completed. (TransactionClosed)")
        End Sub

        Private Sub DoTransaction(ByVal sender As Object, ByVal e As EventArgs)
            Dim host As IDesignerHost = CType(GetService(GetType(IDesignerHost)), IDesignerHost)
            Dim t As DesignerTransaction = host.CreateTransaction("Change Text and Size")

            ' The code within the using statement is considered to be a single transaction.
            ' When the user selects Undo, the system will undo everything executed in this code block. 
            Try
                If (notification_mode) Then
                    System.Windows.Forms.MessageBox.Show("Entering a Designer-Initiated Designer Transaction")
                End If

                Dim someText As PropertyDescriptor = TypeDescriptor.GetProperties(Component)("StringProperty")
                someText.SetValue(Component, "This text was set by the designer for this component.")
                Dim anInteger As PropertyDescriptor = TypeDescriptor.GetProperties(Component)("CountProperty")
                anInteger.SetValue(Component, count)
                count = count + 1

                Exit Try
            Finally
                t.Commit()                
            End Try
            If (notification_mode) Then
                System.Windows.Forms.MessageBox.Show("Designer-Initiated Designer Transaction Completed")
            End If
        End Sub

        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            UnlinkDTNotifications(Me, New EventArgs())
            MyBase.Dispose(disposing)
        End Sub

    End Class
End Namespace 'DesignerTransactionSample

Comentarios

Las transacciones pueden realizar un seguimiento de las acciones que se pueden deshacer más adelante.Transactions can track actions that can be undone later. Los cambios realizados durante una transacción se pueden invertir cancelando una transacción, que intenta invertir automáticamente cada cambio estableciendo cada propiedad modificada en su valor anterior a la modificación.Changes made during a transaction can be reversed by canceling a transaction, which automatically attempts to reverse each change by setting each changed property to its pre-change value. Las transacciones también pueden mejorar el rendimiento durante una serie de operaciones al aplazar las actualizaciones de la pantalla hasta la finalización de la transacción.Transactions can also improve performance during a series of operations by deferring updates to the display until the completion of the transaction.

Cuando una transacción está en curso, algunos componentes aplazan su procesamiento hasta que la transacción haya finalizado escuchando TransactionOpening los TransactionClosed eventos y.When a transaction is in progress, some components defer their processing until the transaction has completed by listening to the TransactionOpening and TransactionClosed events. Por ejemplo, el ventana Propiedades no actualiza su presentación una vez que se ha abierto una transacción hasta que se ha cerrado la transacción.The Properties window, for example, does not update its display after a transaction has opened until the transaction has closed.

Para usar transacciones para operaciones reversibles o varias, haga que el diseñador DesignerTransaction cree un para cada operación o serie de operaciones que deben ser reversibles.To use transactions for reversible or multiple operations, have your designer create a DesignerTransaction for each operation or series of operations which should be reversible. Tenga cuidado de no realizar acciones fuera de las transacciones que podrían impedir que una secuencia de eventos de deshacer se complete correctamente.Be careful not to perform actions outside the transactions that might prevent a sequence of undo events from completing successfully.

Puede obtener un nuevo DesignerTransaction llamando CreateTransaction al método de IDesignerHost.You can obtain a new DesignerTransaction by calling the CreateTransaction method of an IDesignerHost. Asegúrese de obtener cada uno DesignerTransaction de los activos IDesignerHost a fin de integrarlo correctamente con el mecanismo de procesamiento de transacciones del diseñador, en DesignerTransaction lugar de crear un nuevo directamente.Be sure to obtain each DesignerTransaction from the active IDesignerHost in order to correctly integrate with the designer transaction processing mechanism, rather than creating a new DesignerTransaction directly.

Para realizar una acción dentro de una transacción, primero debe crear una transacción.To perform an action within a transaction, you must first create a transaction. A continuación, debe llamar OnComponentChanging al método antes de que se produzcan los cambios o el OnComponentChanged conjunto de cambios y el método después de cada cambio o conjunto de cambios que se produzcan.Then you must call the OnComponentChanging method before each change or set of changes occurs, and the OnComponentChanged method after each change or set of changes occur. Por último, complete y cierre la transacción llamando al Commit método.Finally, complete and close the transaction by calling the Commit method.

Nota

Al realizar cambios en los valores de propiedad, SetValue use el método PropertyDescriptorde, que llama a los métodos de cambio IComponentChangeService de componentes de DesignerTransaction y crea un que representa el cambio automáticamente.When making changes to property values, use the SetValue method of a PropertyDescriptor, which calls the component change methods of the IComponentChangeService and creates a DesignerTransaction representing the change automatically.

Para realizar una transacción, complete los pasos siguientes:To perform a transaction, complete the following steps:

  1. Llame CreateTransaction a para obtener DesignerTransaction un que se puede utilizar para controlar la transacción.Call CreateTransaction to obtain a DesignerTransaction that can be used to control the transaction.

  2. Dentro de try un bloque, para cada acción de la que desea realizar un DesignerTransactionseguimiento con, OnComponentChanging llame al método, realice OnComponentChanged el cambio o los cambios y, a continuación, llame al método para indicar que se han realizado los cambios.Within a try block, for each action that you want to track with a DesignerTransaction, call the OnComponentChanging method, make the change or changes, then call the OnComponentChanged method to signal that the change or changes have been made.

  3. Para completar la transacción, llame Commit a desde dentro finally de un bloque.To complete the transaction, call Commit from within a finally block.

En C#, puede utilizar la using instrucción en lugar de un try/finally bloque, como en el ejemplo siguiente.In C#, you can use the using statement rather than a try/finally block, such as in the following example.

using (host.CreateTransaction() {  
// Insert your code here.  
}  

Para cancelar e intentar revertir una transacción antes de que se haya confirmado, llame al Cancel método.To cancel and attempt to roll back a transaction before it has been committed, call the Cancel method. Cuando se Cancel invoca el método, DesignerTransaction se invierten las acciones de las que realiza el seguimiento para intentar revertir los cambios.When the Cancel method is invoked, the actions tracked by the DesignerTransaction are reversed to attempt to roll back the changes. Para deshacer las acciones que se produjeron como parte de las transacciones anteriores, debe usar el comando Deshacer proporcionado por el entorno de desarrollo.To undo actions that occurred as part of earlier transactions, you must use the undo command provided by the development environment.

Constructores

DesignerTransaction() DesignerTransaction() DesignerTransaction() DesignerTransaction()

Inicializa una nueva instancia de la clase DesignerTransaction sin ninguna descripción.Initializes a new instance of the DesignerTransaction class with no description.

DesignerTransaction(String) DesignerTransaction(String) DesignerTransaction(String) DesignerTransaction(String)

Inicializa una nueva instancia de la clase DesignerTransaction utilizando la descripción de transacción especificada.Initializes a new instance of the DesignerTransaction class using the specified transaction description.

Propiedades

Canceled Canceled Canceled Canceled

Obtiene un valor que indica si se canceló la transacción.Gets a value indicating whether the transaction was canceled.

Committed Committed Committed Committed

Obtiene un valor que indica si se confirmó la transacción.Gets a value indicating whether the transaction was committed.

Description Description Description Description

Obtiene una descripción para la transacción.Gets a description for the transaction.

Métodos

Cancel() Cancel() Cancel() Cancel()

Cancela la transacción e intenta deshacer los cambios realizados por los eventos de la transacción.Cancels the transaction and attempts to roll back the changes made by the events of the transaction.

Commit() Commit() Commit() Commit()

Confirma la transacción.Commits this transaction.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados que usa DesignerTransaction y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the DesignerTransaction and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Libera los recursos asociados a este objeto.Releases the resources associated with this object. Este reemplazo confirma esta transacción si aún no se había confirmado.This override commits this transaction if it was not already committed.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnCancel() OnCancel() OnCancel() OnCancel()

Genera el evento Cancel.Raises the Cancel event.

OnCommit() OnCommit() OnCommit() OnCommit()

Realiza el trabajo real de confirmación de una transacción.Performs the actual work of committing a transaction.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Libera todos los recursos que usa DesignerTransaction.Releases all resources used by the DesignerTransaction.

Seguridad

NamedPermissionSet
para obtener acceso completo a los recursos del sistema.for full access to system resources. Valor de petición InheritanceDemand:.Demand value: InheritanceDemand. Estado asociado:Associated state:

Se aplica a

Consulte también: