获取 RootNodes 的索引

Get index of RootNodes

this example中,索引为0。我的代码有多个根。如何获取选中根的索引?

 private void TreeView_DragItemsCompleted(TreeView sender, TreeViewDragItemsCompletedEventArgs args)
 {
            var children = sourceTreeView.RootNodes[0].Children;

            if (deletedItem != null)
            {
                for (int i = 0; i < children.Count; i++)
                {
                    if (children[i].Content.ToString() == deletedItem.Content.ToString())
                    {
                        children.RemoveAt(i);
                        break;
                    }
                }
            }

            sourceTreeView = null;
            deletedItem = null;
 }

Get index of RootNodes

请参考这个案例。您可以像案例回复一样创建 bind-able 数据源。并为 TreeViewItem 绑定 IsSelected 属性。当项目选择时 IsSelected 值将被更改,因此您可以 foreach 项目源然后获取所选项目的索引。

<TreeViewItem 
    AutomationProperties.Name="{x:Bind Name}"
    IsExpanded="{x:Bind IsExpanded, Mode=TwoWay}"
    IsSelected="{x:Bind IsSelected, Mode=TwoWay}"
    ItemsSource="{x:Bind Children}"
    >
    <StackPanel Orientation="Horizontal">
        <Image Width="20" Source="../Assets/folder.png" />
        <TextBlock Margin="0,0,10,0" />
        <TextBlock Text="{x:Bind Name}" />
    </StackPanel>
</TreeViewItem>

获取索引

 private int GetIndex(ObservableCollection<ExplorerItem> DataSource)
 {
     int index = 0;
     foreach (var item in DataSource)
     {
         if (item.IsSelected == true)
         {
             index = DataSource.IndexOf(item);                 
         }
     }
     return index;
 }