DesignerTransaction Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Permet de grouper une série d’actions au moment du design pour améliorer les performances et permettre l’annulation de la plupart des modifications.
public ref class DesignerTransaction abstract : IDisposable
public abstract class DesignerTransaction : IDisposable
type DesignerTransaction = class
interface IDisposable
Public MustInherit Class DesignerTransaction
Implements IDisposable
- Héritage
-
DesignerTransaction
- Implémente
Exemples
L’exemple de code suivant montre comment créer un DesignerTransaction à partir d’un concepteur. Pour exécuter cet exemple, compilez le code source dans une bibliothèque de classes. Vous devez ajouter une référence à l’assembly System.Design. Dans un nouveau projet, ajoutez une référence à la DLL compilée et ajoutez le composant dans la bibliothèque à la boîte à outils.
Cette fonctionnalité est largement prise en charge dans Visual Studio.
Consultez également Procédure pas à pas : remplissage automatique de la boîte à outils avec des composants personnalisés.
Le concepteur peut éventuellement afficher des notifications sur les événements de transaction du concepteur. Si vous ajoutez une instance du DTComponent
à un formulaire en mode Création, une boîte de message s’affiche pour vous demander si vous souhaitez recevoir des notifications d’événements de transaction du concepteur. Vous pouvez désactiver ces notifications à l’aide du menu contextuel qui s’affiche lorsque vous cliquez avec le bouton droit sur un instance du DTComponent
. Les transactions sont créées lorsque vous modifiez des valeurs à l’aide de la Fenêtre Propriétés. Vous pouvez également demander au concepteur d’effectuer une transaction en cliquant sur Exécuter un exemple de transaction dans le menu contextuel du composant.
#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
Remarques
Les transactions peuvent suivre les actions qui peuvent être annulées ultérieurement. Les modifications apportées au cours d’une transaction peuvent être annulées en annulant une transaction, qui tente automatiquement d’inverser chaque modification en affectant à chaque propriété modifiée sa valeur de pré-modification. Les transactions peuvent également améliorer les performances pendant une série d’opérations en reportant les mises à jour de l’affichage jusqu’à la fin de la transaction.
Lorsqu’une transaction est en cours, certains composants reportent leur traitement jusqu’à ce que la transaction soit terminée en écoutant les TransactionOpening événements et TransactionClosed . Le Fenêtre Propriétés, par exemple, ne met pas à jour son affichage après l’ouverture d’une transaction tant que la transaction n’est pas terminée.
Pour utiliser des transactions pour des opérations réversibles ou multiples, faites en sorte que votre concepteur crée un DesignerTransaction pour chaque opération ou série d’opérations qui doit être réversible. Veillez à ne pas effectuer d’actions en dehors des transactions qui pourraient empêcher une séquence d’événements d’annulation de se terminer correctement.
Vous pouvez obtenir un nouveau en DesignerTransaction appelant la CreateTransaction méthode d’un IDesignerHost. Veillez à obtenir chacun DesignerTransaction à partir de l’actif IDesignerHost afin de s’intégrer correctement au mécanisme de traitement des transactions du concepteur, plutôt que d’en créer directement DesignerTransaction .
Pour effectuer une action dans une transaction, vous devez d’abord créer une transaction. Vous devez ensuite appeler la OnComponentChanging méthode avant chaque modification ou ensemble de modifications, et la OnComponentChanged méthode après chaque modification ou ensemble de modifications se produit. Enfin, terminez et fermez la transaction en appelant la Commit méthode .
Notes
Lorsque vous apportez des modifications aux valeurs de propriété, utilisez la SetValue méthode d’un PropertyDescriptor, qui appelle les méthodes de modification de composant du IComponentChangeService et crée un DesignerTransaction représentant automatiquement la modification.
Pour effectuer une transaction, procédez comme suit :
Appelez CreateTransaction pour obtenir un DesignerTransaction qui peut être utilisé pour contrôler la transaction.
Dans un
try
bloc, pour chaque action que vous souhaitez suivre avec un DesignerTransaction, appelez la OnComponentChanging méthode, apportez la ou les modifications, puis appelez la OnComponentChanged méthode pour signaler que la ou les modifications ont été apportées.Pour terminer la transaction, appelez Commit à partir d’un
finally
bloc.
En C#, vous pouvez utiliser l’instruction using
plutôt qu’un try/finally
bloc, comme dans l’exemple suivant.
using (host.CreateTransaction() {
// Insert your code here.
}
Pour annuler et tenter de restaurer une transaction avant qu’elle n’ait été validée, appelez la Cancel méthode . Lorsque la Cancel méthode est appelée, les actions suivies par le DesignerTransaction sont inversées pour tenter de restaurer les modifications. Pour annuler les actions qui se sont produites dans le cadre de transactions antérieures, vous devez utiliser la commande annuler fournie par l’environnement de développement.
Constructeurs
DesignerTransaction() |
Initialise une nouvelle instance de la classe DesignerTransaction sans description. |
DesignerTransaction(String) |
Initialise une nouvelle instance de la classe DesignerTransaction avec la description de la transaction spécifiée. |
Propriétés
Canceled |
Obtient une valeur indiquant si la transaction a été annulée. |
Committed |
Obtient une valeur indiquant si la transaction a été validée. |
Description |
Obtient une description de la transaction. |
Méthodes
Cancel() |
Annule la transaction et tente de restaurer les modifications apportées par les événements de la transaction. |
Commit() |
Valide cette transaction. |
Dispose(Boolean) |
Libère les ressources non managées utilisées par DesignerTransaction et libère éventuellement les ressources managées. |
Equals(Object) |
Détermine si l'objet spécifié est égal à l'objet actuel. (Hérité de Object) |
Finalize() |
Libère les ressources associées à cet objet. Cette substitution valide cette transaction si elle n’est pas encore validée. |
GetHashCode() |
Fait office de fonction de hachage par défaut. (Hérité de Object) |
GetType() |
Obtient le Type de l'instance actuelle. (Hérité de Object) |
MemberwiseClone() |
Crée une copie superficielle du Object actuel. (Hérité de Object) |
OnCancel() |
Déclenche l’événement |
OnCommit() |
Exécute l’opération réelle de validation d’une transaction. |
ToString() |
Retourne une chaîne qui représente l'objet actuel. (Hérité de Object) |
Implémentations d’interfaces explicites
IDisposable.Dispose() |
Libère toutes les ressources utilisées par DesignerTransaction. |