Mã sau được lấy trực tiếp từ Microsoft tại http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aftercheck%28VS.80%29.aspx.Winforms treeview, đệ quy kiểm tra vấn đề nút con
// 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);
}
}
}
Bạn đặt biểu mẫu này vào biểu mẫu có dạng xem trước và nút gọi_AfterCheck on (ngạc nhiên, ngạc nhiên), sự kiện AfterView của treeview. Sau đó nó kiểm tra đệ quy hoặc bỏ chọn các nút con trên treeview.
Tuy nhiên nếu bạn thực sự dùng thử và nhấp nhiều lần vào cùng một hộp kiểm treeview đủ nhanh, các nút con sẽ kết thúc bằng séc không đồng bộ hóa với cha mẹ. Bạn có thể cần một vài cấp độ của trẻ em với 100 trẻ em trong tổng số cho bản cập nhật giao diện người dùng đủ chậm để nhận thấy điều này xảy ra.
Tôi đã thử một vài điều (chẳng hạn như vô hiệu hóa kiểm soát treeview ở đầu node_AfterCheck và bật lại ở cuối), nhưng vấn đề không đồng bộ hóa vẫn xảy ra.
Bất kỳ ý tưởng nào?
tôi đã đăng workaround của tôi vào một chủ đề con của một này: http://stackoverflow.com/questions/14699102/treeview-check-uncheck-all-child-items/23065225#23065225 –