我创建了一个树视图。将此树视图与数据库绑定。
我希望如果我选择父节点,则应自动选择所有子节点。
在c#我该怎么办?
答案 0 :(得分:3)
这就像你想要的那样:
// 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);
}
}
}
答案 1 :(得分:0)
当您说“已选择”时,您的意思是复选框吗?如果你只是意味着'突出显示',那么这违背了树控件的设计 - 任何时候都只能突出显示一个分支/叶子(显示你当前选择的那个)。如果您的意思是在父分支的框中打勾也会检查所有子框的情况,那么您需要响应单击分支时触发的事件,检查选中的状态,并手动将分支的子项移至设置他们的检查状态。
答案 2 :(得分: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