TreeView.BeforeExpand 事件

定义

在展开树节点前发生。

C#
public event System.Windows.Forms.TreeViewCancelEventHandler BeforeExpand;
C#
public event System.Windows.Forms.TreeViewCancelEventHandler? BeforeExpand;

事件类型

示例

下面的代码示例演示如何更改 的 TreeView 折叠状态,以便所有选中的节点都可见。 首先,折叠所有节点,并为 事件添加 BeforeExpand 处理程序。 接下来,展开所有节点。 事件处理程序 BeforeExpand 确定给定节点是否具有已检查的子节点。 如果节点没有选中的子级,则会取消该节点的扩展。 为了在单击节点旁边的加号时允许标准节点扩展, BeforeExpand 然后删除事件处理程序。

还可以通过处理 BeforeCollapse 事件来实现此行为,如该主题的示例所示。

有关完整示例,请参阅 CheckBoxes 参考主题。

C#
private void showCheckedNodesButton_Click(object sender, EventArgs e)
{
    // Disable redrawing of treeView1 to prevent flickering 
    // while changes are made.
    treeView1.BeginUpdate();

    // Collapse all nodes of treeView1.
    treeView1.CollapseAll();

    // Add the checkForCheckedChildren event handler to the BeforeExpand event.
    treeView1.BeforeExpand += checkForCheckedChildren;

    // Expand all nodes of treeView1. Nodes without checked children are 
    // prevented from expanding by the checkForCheckedChildren event handler.
    treeView1.ExpandAll();

    // Remove the checkForCheckedChildren event handler from the BeforeExpand 
    // event so manual node expansion will work correctly.
    treeView1.BeforeExpand -= checkForCheckedChildren;

    // Enable redrawing of treeView1.
    treeView1.EndUpdate();
}

// Prevent expansion of a node that does not have any checked child nodes.
private void CheckForCheckedChildrenHandler(object sender, 
    TreeViewCancelEventArgs e)
{
    if (!HasCheckedChildNodes(e.Node)) e.Cancel = true;
}

// Returns a value indicating whether the specified 
// TreeNode has checked child nodes.
private bool HasCheckedChildNodes(TreeNode node)
{
    if (node.Nodes.Count == 0) return false;
    foreach (TreeNode childNode in node.Nodes)
    {
        if (childNode.Checked) return true;
        // Recursively check the children of the current child node.
        if (HasCheckedChildNodes(childNode)) return true;
    }
    return false;
}

注解

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅