TreeView.CheckBoxes 属性

获取或设置一个值,用以指示是否在树视图控件中的树节点旁显示复选框。

**命名空间:**System.Windows.Forms
**程序集:**System.Windows.Forms(在 system.windows.forms.dll 中)

语法

声明
Public Property CheckBoxes As Boolean
用法
Dim instance As TreeView
Dim value As Boolean

value = instance.CheckBoxes

instance.CheckBoxes = value
public bool CheckBoxes { get; set; }
public:
property bool CheckBoxes {
    bool get ();
    void set (bool value);
}
/** @property */
public boolean get_CheckBoxes ()

/** @property */
public void set_CheckBoxes (boolean value)
public function get CheckBoxes () : boolean

public function set CheckBoxes (value : boolean)

属性值

如果在树视图控件中的每个树节点旁显示复选框,则为 true;否则为 false。默认为 false

备注

复选框(如果有)显示在树节点标签和树节点 Image 的左侧。利用复选框,用户可以同时选择多个树节点。

TreeViewCheckBoxes 属性设置为 true,而且设置了 StateImageList 属性时,TreeView 中包含的每个 TreeNode 将显示 StateImageList 中的第一和第二幅图像,以分别指示未选中或选中状态。但是如果发生如下情况,显示的图像可能不同:如果节点的 SelectedImageIndex 设置为除 0 或 1 以外的值,并且父 TreeViewCheckBoxes 属性设置为 false,则 SelectedImageIndex 不会自动重置为 -1 以指示它未设置。在这种情况下,将显示位于指示的索引位置的状态图像。如果再次将 CheckBoxes 设置为 true,则显示 StateImageList 的第一、二幅图像,以分别指示选中或未选中状态。

提示

在运行时设置 CheckBoxes 属性时,将重新创建 TreeView 句柄(请参见 Control.RecreateHandle)以更新控件的外观。这将折叠除选定的 TreeNode 之外的所有树节点。

示例

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

此行为还可以通过处理 BeforeCollapse 事件实现,该主题的示例中阐释了这一点。

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits Form
    Private treeView1 As TreeView
    Private showCheckedNodesButton As Button

    Public Sub New()
        treeView1 = New TreeView
        showCheckedNodesButton = New Button

        Me.SuspendLayout()

        ' Initialize treeView1.
        treeView1.Location = New Point(0, 25)
        treeView1.Size = New Size(292, 248)
        treeView1.Anchor = AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Bottom Or AnchorStyles.Right
        treeView1.CheckBoxes = True

        ' Add nodes to treeView1.
        Dim node As TreeNode
        Dim x As Integer
        For x = 0 To 3
            ' Add a root node.
            node = treeView1.Nodes.Add(String.Format("Node{0}", x * 4))
            Dim y As Integer
            For y = 1 To 4
                ' Add a node as a child of the previously added node.
                node = node.Nodes.Add(String.Format("Node{0}", x * 4 + y))
            Next y
        Next x

        ' Set the checked state of one of the nodes to
        ' demonstrate the showCheckedNodesButton button behavior.
        treeView1.Nodes(1).Nodes(0).Nodes(0).Checked = True

        ' Initialize showCheckedNodesButton.
        showCheckedNodesButton.Size = New Size(144, 24)
        showCheckedNodesButton.Text = "Show Checked Nodes"
        AddHandler showCheckedNodesButton.Click, AddressOf showCheckedNodesButton_Click

        ' Initialize the form.
        Me.ClientSize = New Size(292, 273)
        Me.Controls.AddRange(New Control() {showCheckedNodesButton, treeView1})

        Me.ResumeLayout(False)
    End Sub 'New

    <STAThreadAttribute()> _
    Shared Sub Main()
        Application.Run(New Form1)
    End Sub 'Main

    Private Sub showCheckedNodesButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' 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.
        AddHandler treeView1.BeforeExpand, AddressOf 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.
        RemoveHandler treeView1.BeforeExpand, AddressOf CheckForCheckedChildren

        ' Enable redrawing of treeView1.
        treeView1.EndUpdate()
    End Sub 'showCheckedNodesButton_Click

    ' Prevent expansion of a node that does not have any checked child nodes.
    Private Sub CheckForCheckedChildren(ByVal sender As Object, ByVal e As TreeViewCancelEventArgs)
        If Not HasCheckedChildNodes(e.Node) Then
            e.Cancel = True
        End If
    End Sub 'CheckForCheckedChildren

    ' Returns a value indicating whether the specified 
    ' TreeNode has checked child nodes.
    Private Function HasCheckedChildNodes(ByVal node As TreeNode) As Boolean
        If node.Nodes.Count = 0 Then
            Return False
        End If
        Dim childNode As TreeNode
        For Each childNode In node.Nodes
            If childNode.Checked Then
                Return True
            End If
            ' Recursively check the children of the current child node.
            If HasCheckedChildNodes(childNode) Then
                Return True
            End If
        Next childNode
        Return False
    End Function 'HasCheckedChildNodes

End Class 'Form1 
using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : Form
{
    private TreeView treeView1;
    private Button showCheckedNodesButton;
    private TreeViewCancelEventHandler checkForCheckedChildren;

    public Form1()
    {
        treeView1 = new TreeView();
        showCheckedNodesButton = new Button();
        checkForCheckedChildren = 
            new TreeViewCancelEventHandler(CheckForCheckedChildrenHandler);

        this.SuspendLayout();

        // Initialize treeView1.
        treeView1.Location = new Point(0, 25);
        treeView1.Size = new Size(292, 248);
        treeView1.Anchor = AnchorStyles.Top | AnchorStyles.Left | 
            AnchorStyles.Bottom | AnchorStyles.Right;
        treeView1.CheckBoxes = true;

        // Add nodes to treeView1.
        TreeNode node;
        for (int x = 0; x < 3; ++x)
        {
            // Add a root node.
            node = treeView1.Nodes.Add(String.Format("Node{0}", x*4));
            for (int y = 1; y < 4; ++y)
            {
                // Add a node as a child of the previously added node.
                node = node.Nodes.Add(String.Format("Node{0}", x*4 + y));
            }
        }

        // Set the checked state of one of the nodes to
        // demonstrate the showCheckedNodesButton button behavior.
        treeView1.Nodes[1].Nodes[0].Nodes[0].Checked = true;

        // Initialize showCheckedNodesButton.
        showCheckedNodesButton.Size = new Size(144, 24);
        showCheckedNodesButton.Text = "Show Checked Nodes";
        showCheckedNodesButton.Click += 
            new EventHandler(showCheckedNodesButton_Click);

        // Initialize the form.
        this.ClientSize = new Size(292, 273);
        this.Controls.AddRange(new Control[] 
            { showCheckedNodesButton, treeView1 } );

        this.ResumeLayout(false);
    }

    [STAThreadAttribute()]
    static void Main() 
    {
        Application.Run(new Form1());
    }

    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;
    }

}
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class Form1: public Form
{
private:
   TreeView^ treeView1;
   Button^ showCheckedNodesButton;
   TreeViewCancelEventHandler^ checkForCheckedChildren;

public:
   Form1()
   {
      treeView1 = gcnew TreeView;
      showCheckedNodesButton = gcnew Button;
      checkForCheckedChildren = gcnew TreeViewCancelEventHandler( this, &Form1::CheckForCheckedChildrenHandler );
      this->SuspendLayout();
      
      // Initialize treeView1.
      treeView1->Location = Point(0,25);
      treeView1->Size = System::Drawing::Size( 292, 248 );
      treeView1->Anchor = static_cast<AnchorStyles>(AnchorStyles::Top | AnchorStyles::Left | AnchorStyles::Bottom | AnchorStyles::Right);
      treeView1->CheckBoxes = true;
      
      // Add nodes to treeView1.
      TreeNode^ node;
      for ( int x = 0; x < 3; ++x )
      {
         
         // Add a root node.
         node = treeView1->Nodes->Add( String::Format( "Node{0}", x * 4 ) );
         for ( int y = 1; y < 4; ++y )
         {
            
            // Add a node as a child of the previously added node.
            node = node->Nodes->Add( String::Format( "Node{0}", x * 4 + y ) );

         }
      }
      
      // Set the checked state of one of the nodes to
      // demonstrate the showCheckedNodesButton button behavior.
      treeView1->Nodes[ 1 ]->Nodes[ 0 ]->Nodes[ 0 ]->Checked = true;
      
      // Initialize showCheckedNodesButton.
      showCheckedNodesButton->Size = System::Drawing::Size( 144, 24 );
      showCheckedNodesButton->Text = "Show Checked Nodes";
      showCheckedNodesButton->Click += gcnew EventHandler( this, &Form1::showCheckedNodesButton_Click );
      
      // Initialize the form.
      this->ClientSize = System::Drawing::Size( 292, 273 );
      array<Control^>^temp0 = {showCheckedNodesButton,treeView1};
      this->Controls->AddRange( temp0 );
      this->ResumeLayout( false );
   }

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.
   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.
   bool HasCheckedChildNodes( TreeNode^ node )
   {
      if ( node->Nodes->Count == 0 )
            return false;

      System::Collections::IEnumerator^ myEnum = node->Nodes->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         TreeNode^ childNode = safe_cast<TreeNode^>(myEnum->Current);
         if ( childNode->Checked )
                  return true;

         // Recursively check the children of the current child node.
         if ( HasCheckedChildNodes( childNode ) )
                  return true;
      }

      return false;
   }
};

int main()
{
   Application::Run( gcnew Form1 );
}
import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class Form1 extends Form
{
    private TreeView treeView1;
    private Button showCheckedNodesButton;
    private TreeViewCancelEventHandler checkForCheckedChildren;

    public Form1()
    {
        treeView1 = new TreeView();
        showCheckedNodesButton = new Button();
        checkForCheckedChildren =
            new TreeViewCancelEventHandler(CheckForCheckedChildrenHandler);

        this.SuspendLayout();
        // Initialize treeView1.
        treeView1.set_Location(new Point(0, 25));
        treeView1.set_Size(new Size(292, 248));
        treeView1.set_Anchor(AnchorStyles.Top | AnchorStyles.Left
            | AnchorStyles.Bottom | AnchorStyles.Right);
        treeView1.set_CheckBoxes(true);
        // Add nodes to treeView1.
        TreeNode node;
        for (int x = 0; x < 3; ++x) {
            // Add a root node.
            node = treeView1.get_Nodes().Add(String.Format
                ("Node{0}", (Int32)(x * 4)));
            for (int y = 1; y < 4; ++y) {
                // Add a node as a child of the previously added node.
                node = node.get_Nodes().Add(String.Format
                    ("Node{0}", (Int32)(x * 4 + y)));
            }
        }
        // Set the checked state of one of the nodes to
        // demonstrate the showCheckedNodesButton button behavior.
        treeView1.get_Nodes().get_Item(1).get_Nodes().get_Item(0).
            get_Nodes().get_Item(0).set_Checked(true);
        // Initialize showCheckedNodesButton.
        showCheckedNodesButton.set_Size(new Size(144, 24));
        showCheckedNodesButton.set_Text("Show Checked Nodes");
        showCheckedNodesButton.add_Click(
            new EventHandler(showCheckedNodesButton_Click));
        // Initialize the form.
        this.set_ClientSize(new Size(292, 273));
        this.get_Controls().AddRange(new Control[]
            { showCheckedNodesButton, treeView1 });

        this.ResumeLayout(false);
    } //Form1

    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main

    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.add_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.remove_BeforeExpand(checkForCheckedChildren);
        // Enable redrawing of treeView1.
        treeView1.EndUpdate();
    } //showCheckedNodesButton_Click

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

    // Returns a value indicating whether the specified 
    // TreeNode has checked child nodes.
    private boolean HasCheckedChildNodes(TreeNode node)
    {
        if (node.get_Nodes().get_Count() == 0) {
            return false;
        }
        for (int iCtr = 0; iCtr < node.get_Nodes().get_Count(); iCtr++) {
            TreeNode childNode = node.get_Nodes().get_Item(iCtr);
            if (childNode.get_Checked()) {
                return true;
            }
            // Recursively check the children of the current child node.
            if (HasCheckedChildNodes(childNode)) {
                return true;
            }
        }
        return false;
    } //HasCheckedChildNodes
} //Form1

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、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

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

TreeView 类
TreeView 成员
System.Windows.Forms 命名空间
TreeNode.Checked 属性