在C#中,使用WinForms或WPF的TreeView控件可以实现节点展开和折叠。以下是在WinForms和WPF中实现这一功能的方法:
WinForms:
private TreeView treeView;
public Form1()
{
InitializeComponent();
treeView = new TreeView();
treeView.Dock = DockStyle.Fill;
this.Controls.Add(treeView);
}
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);
}
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;
}
}
private void Form1_Load(object sender, EventArgs e)
{
AddNodes();
treeView.BeforeExpand += treeView_BeforeExpand;
treeView.BeforeCollapse += treeView_BeforeCollapse;
}
WPF:
<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>
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);
}
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;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
AddNodes();
treeView.BeforeExpand += treeView_BeforeExpand;
treeView.BeforeCollapse += treeView_BeforeCollapse;
}
这样,在WinForms和WPF的TreeView控件中,当用户点击节点时,节点的子节点将展开或折叠。