经过一整天的工作后不确定是不是我......或者WPF类型的树有什么不同。我正在向树中添加数据,然后当它是父节点时需要添加其子节点,但SelectedItem始终为null!
任何评论或指示都会有所帮助。
感谢。
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.
答案 0 :(得分: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;
}
}
}
}