在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控件中,當用戶點擊節點時,節點的子節點將展開或折疊。