WPF TreeView 后台C#选中指定的Item, 需要遍历_51CTO博客_c# treeview选中节点

private TreeViewItem FindTreeViewItem(ItemsControl container, object item)

        {

if (null == container || null == item)

            {

return null;

            }

if (container.DataContext == item)

            {

return container as TreeViewItem;

            }

int count = container.Items.Count;

for (int i = 0; i < count; i++)

            {

TreeViewItem subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);

if (null == subContainer)

                {

continue;

                }

// Search the next level for the object.

TreeViewItem resultContainer = FindTreeViewItem(subContainer, item);

if (null != resultContainer)

                {

return resultContainer;

                }

            }

return null;

        }

/////使用上述方法遍历 , 然后设置IsSelected属性

private static void SelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

//

SelectedProtocolControl spc = d as SelectedProtocolControl;

if (null != spc)

            {

if (e.NewValue != spc.trvSelectedProtocol.SelectedItem)

                {

//TreeViewItem tviNew = spc.trvSelectedProtocol.ItemContainerGenerator.ContainerFromItem(e.NewValue) as TreeViewItem;

TreeViewItem tviNew = spc.FindTreeViewItem(spc.trvSelectedProtocol, e.NewValue);

if (null != tviNew)

                    {

tviNew.IsSelected = true;

                    }

                }

if (null != e.OldValue)

                {

//TreeViewItem tviOld = spc.trvSelectedProtocol.ItemContainerGenerator.ContainerFromItem(e.OldValue) as TreeViewItem;

TreeViewItem tviOld = spc.FindTreeViewItem(spc.trvSelectedProtocol, e.OldValue);

if (null != tviOld)

                    {

tviOld.IsSelected = false;

                    }

                }

            }

System.Diagnostics.Debug.WriteLine("SelectedItemChanged...");

        }


原网址: 访问
创建于: 2024-06-19 18:49:25
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论