2012-03-27 176 views

回答

0

當你說'選擇'時,你的意思是用複選框嗎?如果您只是指「突出顯示」,那麼這與樹形控件的設計不符 - 每次只能突出顯示一個分支/葉子(以顯示您當前選擇的分支)。如果您的意思是在父分支的框中進行檢查也會對所有孩子的方框進行檢查,那麼您需要響應點擊分支時觸發的事件,檢查選中的狀態並手動將分支的孩子移至設置他們的檢查狀態。

2

這有點像你想:

// Updates all child tree nodes recursively. 
private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked) 
{ 
    foreach(TreeNode node in treeNode.Nodes) 
    { 
     node.Checked = nodeChecked; 
     if(node.Nodes.Count > 0) 
     { 
     // If the current node has child nodes, call the CheckAllChildsNodes method recursively. 
     this.CheckAllChildNodes(node, nodeChecked); 
     } 
    } 
} 

// NOTE This code can be added to the BeforeCheck event handler instead of the AfterCheck event. 
// After a tree node's Checked property is changed, all its child nodes are updated to the same value. 
private void node_AfterCheck(object sender, TreeViewEventArgs e) 
{ 
    // The code only executes if the user caused the checked state to change. 
    if(e.Action != TreeViewAction.Unknown) 
    { 
     if(e.Node.Nodes.Count > 0) 
     { 
     /* Calls the CheckAllChildNodes method, passing in the current 
     Checked value of the TreeNode whose checked state changed. */ 
     this.CheckAllChildNodes(e.Node, e.Node.Checked); 
     } 
    } 
} 
0

上面的代碼功能不正常 - 這是從MSDN AfterCheck事件主題然而事件未在雙擊可靠解僱複製/粘貼代碼 - 你需要混合它禁用雙擊的代碼 - 這是我在MSDN中找到的解決方法:

public class MyTreeView : TreeView 
{ 
    #region Constructors 

    public MyTreeView() 
    { 
    } 

    #endregion 

    #region Overrides 

    protected override void WndProc(ref Message m) 
    { 
     // Suppress WM_LBUTTONDBLCLK on checkbox 
     if (m.Msg == 0x0203 && CheckBoxes && IsOnCheckBox(m)) 
     { 
      m.Result = IntPtr.Zero; 
     } 
     else 
     { 
      base.WndProc(ref m); 
     } 
    } 

    #endregion 

    #region Double-click check 

    private int GetXLParam(IntPtr lParam) 
    { 
     return lParam.ToInt32() & 0xffff; 
    } 

    private int GetYLParam(IntPtr lParam) 
    { 
     return lParam.ToInt32() >> 16; 
    } 

    private bool IsOnCheckBox(Message m) 
    { 
     int x = GetXLParam(m.LParam); 
     int y = GetYLParam(m.LParam); 
     TreeNode node = GetNodeAt(x, y); 
     if (node == null) 
      return false; 
     int iconWidth = ImageList == null ? 0 : ImageList.ImageSize.Width; 
     int right = node.Bounds.Left - 4 - iconWidth; 
     int left = right - CHECKBOX_WIDTH; 
     return left <= x && x <= right; 
    } 

    const int CHECKBOX_WIDTH = 12; 

    #endregion