1、递归
下面是Winform的递归添加菜单栏数据,数据设置好父子id方便递归使用
在TreeView的控件窗口加载时,调用递归加载菜单
private void LoadTvMenu(){this.nodeList = objService.GetAllMenu(); // 通过Service得到全部数据// 创建一个根节点this.tv_MenuList.Nodes.Clear(); // 亲空所有节点// 这个是TreeView的节点TreeNode rootNode = new TreeNode();rootNode.Text = "学员管理系统";rootNode.Tag = "0"; // 暂时没什么用rootNode.ImageIndex = 0; // 设置根节点现实的图片this.tv_MenuList.Nodes.Add(rootNode); // 将根节点添加到treeview根节点// 基于递归方式添加所有子节点CreateChildNode(rootNode, "0");}private void CreateChildNode(TreeNode parentNode, string preId){var nodes = from list in nodeListwhere list.ParentId.Equals(preId)select list;foreach (var item in nodes){TreeNode node = new TreeNode();node.Text = item.MenuName;node.Tag = item.MenuCode;// 设置节点图表if (item.ParentId == "0"){node.ImageIndex = 1;}else{node.ImageIndex = 3;}parentNode.Nodes.Add(node); // 给父节点添加上这个子节点// 递归调用CreateChildNode(node, item.MenuId.ToString());this.tv_MenuList.Nodes[0].Expand(); // 将一级目录全部展开this.tv_MenuList.ExpandAll();}}
在WPF中也是差不多的可以用递归实现加载TreeView
2、WPF中可以使用HierarchicalDataTemplate非常方便
创建数据类
public class ListLeagueList : ObservableCollection<League>
{List<League> leagues = new List<League>();List<Division> divisions = new List<Division>();List<Team> teams = new List<Team>();public ListLeagueList(){teams.Add(new Team() { Name = "Team 1" });teams.Add(new Team() { Name = "Team 2" });teams.Add(new Team() { Name = "Team 3" });teams.Add(new Team() { Name = "Team 4" });divisions.Add(new Division() { Name = "Division 1", Teams = teams });divisions.Add(new Division() { Name = "Division 2", Teams = teams });divisions.Add(new Division() { Name = "Division 3", Teams = teams });Add(new League() { Name = "League a", Divisions = divisions });Add(new League() { Name = "League b", Divisions = divisions });Add(new League() { Name = "League c", Divisions = divisions });}
}
view中 设置下一个子集合为ItemsSource
<DockPanel><DockPanel.Resources><local:ListLeagueList x:Key="myList" /><HierarchicalDataTemplate DataType="{x:Type models:League}" ItemsSource="{Binding Divisions}"><TextBlock Text="{Binding Path=Name}" /></HierarchicalDataTemplate><HierarchicalDataTemplate DataType="{x:Type models:Division}" ItemsSource="{Binding Teams}"><TextBlock Text="{Binding Path=Name}" /></HierarchicalDataTemplate><!-- 最后一个没有ItemsSource --><HierarchicalDataTemplate DataType="{x:Type models:Team}"><TextBlock Text="{Binding Path=Name}" /></HierarchicalDataTemplate></DockPanel.Resources><Menux:Name="menu1"Margin="10"DockPanel.Dock="Top"><MenuItem Header="我的足球联赛" ItemsSource="{Binding Source={StaticResource myList}}" /></Menu><TreeView x:Name="treeView1"><TreeViewItem Header="我的足球联赛" ItemsSource="{Binding Source={StaticResource myList}}" /></TreeView></DockPanel>
使用HierarchDataTemplate后可以显示多层的控件都可以使用
-- 这里的ItemsSource是集合,使用其它方式绑定上也是一样的;HierarchicalDataTemplate就是独立于这个集合的,检测到合适就起作用