我有一个稍微不同的设置,我通过在 datagridview 中选择一个项目来控制 TreeView 中突出显示的项目。这不是最优雅的方法,但它确实有效。
总之:
1.) 从源 TreeView、其他控件或其他地方获取索引 2.) 展开目标 TreeView 中的所有节点 3.) 遍历目标中的树节点,直到达到索引 4.) 设置 TreeView.SelectedNode = "找到” 5.) 将焦点设置在 TreeView
private void selectTreeViewItem(int dataGridViewRowIndex)
{
expandAllTreeViewNodes();
setTreeViewItem(dataGridViewRowIndex);
}
private void setTreeViewItem(int dataGridViewRowIndex)
{
int iterator = 0;
TreeNode tempNode = testStepTreeView.Nodes[iterator];
//don't need to actually return the integer...
iterator = findNode(tempNode, dataGridViewRowIndex, iterator);
testStepTreeView.Focus();
nodeFound = false;
}
private void expandAllTreeViewNodes()
{
if (testStepTreeView.Nodes.Count != 0)
{
foreach (TreeNode x in testStepTreeView.Nodes)
{
expandNode(x);
}
}
}
private void expandNode(TreeNode x)
{
if (x.IsExpanded == false)
{
x.Expand();
}
if (x.Nodes.Count > 0)
{
foreach (TreeNode y in x.Nodes)
{
expandNode(y);
}
}
}
private int findNode(TreeNode tempNode, int dataGridViewRowIndex, int iterator)
{
if (iterator > dataGridViewRowIndex)
{
return iterator;
}
if (iterator == dataGridViewRowIndex)
{
testStepTreeView.SelectedNode = tempNode;
nodeFound = true;
return iterator;
}
if (tempNode.Nodes.Count != 0)
{
iterator++;
if (iterator > dataGridViewRowIndex)
{
return iterator;
}
if (nodeFound == false)
{
iterator = findNode(tempNode.Nodes[0], dataGridViewRowIndex, iterator);
}
}
if (tempNode.NextNode != null)
{
iterator++;
if (iterator > dataGridViewRowIndex)
{
return iterator;
}
if (nodeFound == false)
{
iterator = findNode(tempNode.NextNode, dataGridViewRowIndex, iterator);
}
}
return iterator;
}