1. 程式人生 > >C# 父子選單填充到TreeNode(並根據遞迴次數設定節點選中狀態)

C# 父子選單填充到TreeNode(並根據遞迴次數設定節點選中狀態)

/// <summary>
/// 子節點選中的遞迴次數
/// </summary>
static int recursionCount = 0;

/// <summary>
/// 設定選單到TreeNode
/// </summary>
/// <param name="menuItms">包含子節點的頂層選單</param>
/// <param name="nodes">目標節點</param>
/// <param name="bImageIndex">圖片</param>
/// <param name="setChildNodeCheckedStatus">是否設定子節點選中狀態</param>
public static void MapMenuItm2TreeNodes(IList<Sys_MenuItm> menuItms, TreeNodeCollection nodes, bool bImageIndex ,bool setChildNodeCheckedStatus = false)
{
    if (menuItms == null || menuItms.Count < 1)
        return;
    for (int i = 0; i < menuItms.Count; i++)
    {
        TreeNode node = new TreeNode(menuItms[i].MenuName);
        node.Tag = menuItms[i];
        menuItms[i].Tag = node;
        if (bImageIndex)  // 設定節點顯示圖片
        {
            node.ImageIndex = menuItms[i].LeafFlg ? 0 : 1;
            node.SelectedImageIndex = node.ImageIndex;
        }
        if (setChildNodeCheckedStatus) //設定子節點的選中狀態
        {                  
            nodes.Add(node);
            MapMenuItm2TreeNodes(menuItms[i].Children, node.Nodes, bImageIndex,true);
            if(menuItms[i].CheckedFlg)
            {
                node.Checked = true;
                recursionCount++;
            }
            //判斷該節點的子節點是否全被選中
            if (menuItms[i].Children.Count != 0 )
            {                      
                if (menuItms[i].Children.Count == recursionCount)
                {
                    node.Checked = true;
                }
                recursionCount = 0;
            }
         }
         else
         {
             nodes.Add(node);
             MapMenuItm2TreeNodes(menuItms[i].Children, node.Nodes, bImageIndex);
         }
    }
}