0

经过一整天的工作后不确定是我……或者 WPF 类型的树有什么不同。我正在向树中添加数据,然后当它是父节点时需要添加其子节点,但 SelectedItem 始终为空!

任何评论或指示都会有所帮助。

谢谢。

XAML:

  <TreeView x:Name="TreeView1" Grid.Row="0">
  </TreeView>

Code:
       TreeView myTree = FindChild<TreeView>(Application.Current.MainWindow, "TreeView1");

       myTree.Items.Add(ObjEmployee.Tag);
       TreeViewItem tvi = (TreeViewItem) myTree.SelectedItem;  
//my assumption was that when an item is added to tree most recent used node will be selected but it seems something is avoiding it or maybe works in a different way.
4

1 回答 1

0

你应该发布一些代码片段..我不明白你需要什么。

如果您使用分层模板 ( http://msdn.microsoft.com/en-us/library/ms742521.aspx ) SelectIedtem 的对象将是您放入 ItemsSource 的数据之一


否则,“SelectedItem”可以是您放在树视图中的任何类型的可视组件。

var treeItem = myTree.SelectedItem;
if (treeItem != null)
    treeitem.GetType().Name;

通常在树视图中使用 TreeViewItem,所有对象都在 treeViewItem.Items


(编辑)你可以试试这个:

            var result = FindVisualChildren<TreeViewItem>(treeView);

            foreach (var item in result)
            {
                if (item.IsSelected)
                {
                    ....
                }
            }

    public static IEnumerable<T> FindVisualChildren<T>(FrameworkElement depObj) where T : FrameworkElement
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                FrameworkElement child = (FrameworkElement)VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }
于 2012-06-26T03:01:39.417 回答