DesignerTransaction 类
提供一种方法来对一系列的设计时操作进行分组,从而提高性能并使得大多数类型的更改都能撤消。
**命名空间:**System.ComponentModel.Design
**程序集:**System(在 system.dll 中)
语法
声明
Public MustInherit Class DesignerTransaction
Implements IDisposable
用法
Dim instance As DesignerTransaction
public abstract class DesignerTransaction : IDisposable
public ref class DesignerTransaction abstract : IDisposable
public abstract class DesignerTransaction implements IDisposable
public abstract class DesignerTransaction implements IDisposable
备注
事务可以跟踪以后能撤消的操作。在事务处理过程中作出的更改可通过取消事务来撤消,这样,每项已更改的属性将自动设置为更改前的值,从而撤消每一更改。事务还可以提高系列操作的性能,方法是将显示更新的操作推迟到事务完成之后。
当事务正在进行时,某些组件会通过侦听 TransactionOpening 和 TransactionClosed 事件将其处理延迟到事务完成之后。例如,在打开事务之后,关闭事务之前,“属性”窗口不会更新其显示。
若要对可以撤消的操作或多个操作使用事务,可让设计器为每个应当可以撤消的操作或操作系列创建 DesignerTransaction。注意不要在事务外执行操作,因为这可能会防碍撤消事件序列成功完成。
您可以通过调用 IDesignerHost 的 CreateTransaction 方法来获得新的 DesignerTransaction。为了与设计器事务处理机制正确集成,请确保从活动的 IDesignerHost 获得每个 DesignerTransaction,而不是直接创建新的 DesignerTransaction。
若要在事务内执行操作,必须首先创建事务。然后,必须在每个更改或每组更改发生之前调用 OnComponentChanging 方法,并在每个更改或每组更改发生之后调用 OnComponentChanged 方法。最后,通过调用 Commit 方法完成并关闭事务。
提示
当对属性值进行更改时,请使用 PropertyDescriptor 的 SetValue 方法,它调用 IComponentChangeService 的组件更改方法并自动创建表示更改的 DesignerTransaction。
若要执行事务,请完成以下步骤:
调用 CreateTransaction 以获取可用来控制事务的 DesignerTransaction。
在 try 块内,对每个要通过 DesignerTransaction 跟踪的操作调用 OnComponentChanging 方法,进行更改,然后调用 OnComponentChanged 方法来发出已作出更改的信号。
若要完成事务,请从 finally 块内调用 Commit。
在 C# 中,可以使用 using 语句而不是 try/finally 块,如下面的示例所示。
using (host.CreateTransaction() {
// Insert your code here.
}
若要在提交事务前取消和尝试回滚事务,请调用 Cancel 方法。当调用 Cancel 方法时,将撤消由 DesignerTransaction 跟踪的操作,以回滚更改。若要撤消作为先前事务的一部分而发生的操作,必须使用开发环境提供的撤消命令。
提示
应用于此类的 HostProtectionAttribute 属性 (Attribute) 具有以下 Resources 属性 (Property) 值:SharedState。HostProtectionAttribute 不影响桌面应用程序(桌面应用程序一般通过双击图标,键入命令或在浏览器中输入 URL 启动)。有关更多信息,请参见 HostProtectionAttribute 类或 SQL Server 编程和宿主保护属性。
示例
下面的代码示例程序演示如何从设计器创建 DesignerTransaction。设计器可以选择显示有关设计器事务事件的通知。若要运行此示例,请将源代码编译为类库,向项目添加一个对编译好的 DLL 的引用,并将库中的组件添加到“工具箱”。
Visual Studio 中对此功能提供了广泛的支持。
演练:使用自定义组件自动填充工具箱
演练:使用自定义组件自动填充工具箱
演练:使用自定义组件自动填充工具箱
演练:使用自定义组件自动填充工具箱
在设计模式下将 DTComponent
的实例添加到窗体中,这时将显示一个消息框,询问您是否愿意接收设计器事务事件通知。您可以使用右击 DTComponent
实例时显示的快捷菜单来切换这些通知。使用“属性”窗口更改值时将创建事务。您还可通过单击该组件快捷菜单上的“执行示例事务”来让设计器执行事务。
Imports System
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 'InitializeComponent
End Class 'DTComponent
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 'Initialize
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 Not (host Is Nothing) Then
notification_mode = True
AddHandler host.TransactionOpened, AddressOf OnDesignerTransactionOpened
AddHandler host.TransactionClosed, AddressOf OnDesignerTransactionClosed
End If
End If
End Sub 'LinkDTNotifications
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 Not (host Is Nothing) Then
notification_mode = False
RemoveHandler host.TransactionOpened, AddressOf Me.OnDesignerTransactionOpened
RemoveHandler host.TransactionClosed, AddressOf Me.OnDesignerTransactionClosed
End If
End If
End Sub 'UnlinkDTNotifications
Private Sub OnDesignerTransactionOpened(ByVal sender As Object, ByVal e As EventArgs)
System.Windows.Forms.MessageBox.Show("A Designer Transaction was started. (TransactionOpened)")
End Sub 'OnDesignerTransactionOpened
Private Sub OnDesignerTransactionClosed(ByVal sender As Object, ByVal e As DesignerTransactionCloseEventArgs)
System.Windows.Forms.MessageBox.Show("A Designer Transaction was completed. (TransactionClosed)")
End Sub 'OnDesignerTransactionClosed
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 'DoTransaction
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
UnlinkDTNotifications(Me, New EventArgs())
MyBase.Dispose(disposing)
End Sub 'Dispose
End Class 'DTDesigner
End Namespace 'DesignerTransactionSample
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);
}
}
}
#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;
}
}
};
.NET Framework 安全性
- NamedPermissionSet 用于对系统资源进行完全访问。要求值:InheritanceDemand。关联状态:FullTrust
继承层次结构
System.Object
System.ComponentModel.Design.DesignerTransaction
线程安全
此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。
平台
Windows 98、Windows 2000 SP4、Windows Millennium Edition、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition
.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求。
版本信息
.NET Framework
受以下版本支持:2.0、1.1、1.0
请参见
参考
DesignerTransaction 成员
System.ComponentModel.Design 命名空间
IDesignerHost
IComponentChangeService
PropertyDescriptor 类