c# treeview怎樣實(shí)現(xiàn)節(jié)點(diǎn)展開(kāi)折疊

c#
小樊
81
2024-11-19 03:06:35

在C#中,使用WinForms或WPF的TreeView控件可以實(shí)現(xiàn)節(jié)點(diǎn)展開(kāi)和折疊。以下是在WinForms和WPF中實(shí)現(xiàn)這一功能的方法:

WinForms:

  1. 首先,在WinForms應(yīng)用程序中添加一個(gè)TreeView控件。
private TreeView treeView;

public Form1()
{
    InitializeComponent();

    treeView = new TreeView();
    treeView.Dock = DockStyle.Fill;
    this.Controls.Add(treeView);
}
  1. 為T(mén)reeView控件添加節(jié)點(diǎn)。
private void AddNodes()
{
    TreeNode node1 = new TreeNode("Node 1");
    TreeNode node2 = new TreeNode("Node 2");
    TreeNode node3 = new TreeNode("Node 3");

    node1.Nodes.Add(node2);
    node1.Nodes.Add(node3);

    treeView.Nodes.Add(node1);
}
  1. 為T(mén)reeView控件添加節(jié)點(diǎn)展開(kāi)和折疊的事件處理程序。
private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    if (!e.Node.Nodes.Count.Equals(0))
    {
        e.Cancel = false;
    }
}

private void treeView_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
    if (!e.Node.Nodes.Count.Equals(0))
    {
        e.Cancel = false;
    }
}
  1. 在窗體的Load事件處理程序中添加節(jié)點(diǎn)并綁定事件處理程序。
private void Form1_Load(object sender, EventArgs e)
{
    AddNodes();
    treeView.BeforeExpand += treeView_BeforeExpand;
    treeView.BeforeCollapse += treeView_BeforeCollapse;
}

WPF:

  1. 首先,在WPF應(yīng)用程序中添加一個(gè)TreeView控件。
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TreeView x:Name="treeView" HorizontalAlignment="Left" Height="278" Margin="10,10,0,0" VerticalAlignment="Top" Width="493"/>
    </Grid>
</Window>
  1. 為T(mén)reeView控件添加節(jié)點(diǎn)。
private void AddNodes()
{
    TreeNode node1 = new TreeNode("Node 1");
    TreeNode node2 = new TreeNode("Node 2");
    TreeNode node3 = new TreeNode("Node 3");

    node1.Nodes.Add(node2);
    node1.Nodes.Add(node3);

    treeView.Items.Add(node1);
}
  1. 為T(mén)reeView控件添加節(jié)點(diǎn)展開(kāi)和折疊的事件處理程序。
private void treeView_BeforeExpand(object sender, CanExpandChangedEventArgs e)
{
    if (!e.Node.HasChildren)
    {
        e.CanExpand = false;
    }
}

private void treeView_BeforeCollapse(object sender, CanExpandChangedEventArgs e)
{
    if (!e.Node.HasChildren)
    {
        e.CanExpand = false;
    }
}
  1. 在窗體的Load事件處理程序中添加節(jié)點(diǎn)并綁定事件處理程序。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    AddNodes();
    treeView.BeforeExpand += treeView_BeforeExpand;
    treeView.BeforeCollapse += treeView_BeforeCollapse;
}

這樣,在WinForms和WPF的TreeView控件中,當(dāng)用戶(hù)點(diǎn)擊節(jié)點(diǎn)時(shí),節(jié)點(diǎn)的子節(jié)點(diǎn)將展開(kāi)或折疊。

0