Delphi中BeginUpdate和EndUpdate作用

来源:互联网 发布:项目进度跟踪软件 编辑:程序博客网 时间:2024/05/18 01:13
 许多 Windows 窗体控件(例如,ListView 和 TreeView 控件)实现了 BeginUpdate 和EndUpdate 方法,它们在操纵基础数据或控件属性时取消了控件的重新绘制。通过使用BeginUpdate 和 EndUpdate 方法,您可以对控件进行重大更改,并且避免在应用这些更改时让控件经常重新绘制自身。此类重新绘制会导致性能显著降低,并且用户界面闪烁且不反应。例如,如果您的应用程序具有一个要求添加大量节点项的树控件,则您应该调用 BeginUpdate,添加所有必需的节点项,然后调用 EndUpdate。下面的代码示例显示了一个树控件,该控件用于显示许多个客户的层次结构表示形式及其定单信息。
  [C#]
  // Suppress repainting the TreeView until all the objects have been created.
  TreeView1.BeginUpdate();
  // Clear the TreeView.
  TreeView1.Nodes.Clear();
  // Add a root TreeNode for each Customer object in the ArrayList.
  foreach( Customer customer2 in customerArray )
  {
  TreeView1.Nodes.Add( new TreeNode( customer2.CustomerName ) );
  // Add a child TreeNode for each Order object in the current Customer.
  foreach( Order order1 in customer2.CustomerOrders )
  {
  TreeView1.Nodes[ customerArray.IndexOf(customer2) ].Nodes.Add(
  new TreeNode( customer2.CustomerName + "." + order1.OrderID ) );
  }
  }
  // Begin repainting the TreeView.
  TreeView1.EndUpdate();
  [Visual Basic .NET]
  ' Suppress repainting the TreeView until all the objects have been
  created.
  TreeView1.BeginUpdate()
  ' Clear the TreeView
  TreeView1.Nodes.Clear()
  ' Add a root TreeNode for each Customer object in the ArrayList
  For Each customer2 As Customer In customerArray
  TreeView1.Nodes.Add(New TreeNode(customer2.CustomerName))
  ' Add a child TreeNode for each Order object in the current Customer.
  For Each order1 As Order In customer2.CustomerOrders
  TreeView1.Nodes(Array.IndexOf(customerArray, customer2)).Nodes.Add( _
  New TreeNode(customer2.CustomerName & "." & order1.OrderID))
  Next
  Next
  ' Begin repainting the TreeView.
  TreeView1.EndUpdate()
  即使在您不希望向控件添加许多对象时,您也应该使用 BeginUpdate 和 EndUpdate 方法。在大多数情况下,您在运行之前将不知道要添加的项的确切个数。因此,为了妥善处理大量数据以及应付将来的要求,您应该总是调用 BeginUpdate 和 EndUpdate 方法。注调用 Windows 窗体控件使用的许多 Collection 类的 AddRange 方法时,将自动为您调用 BeginUpdate 和 EndUpdate 方法。
原创粉丝点击