我只想从TreeView访问所选子项的父元素。它是一个WPF应用程序,我需要C#代码来将所选子项及其父项作为字符串。函数是:
private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//How to get the selected child and parents as strings
}
答案 0 :(得分:0)
如果您不使用MVVM,以下内容将为您提供用户点击的项目和父项目的内容。
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeView the_tree = e.OriginalSource as TreeView;
TreeViewItem clicked_item = the_tree.SelectedItem as TreeViewItem;
MessageBox.Show(clicked_item.Header.ToString());
TreeViewItem clicked_parent = clicked_item.Parent as TreeViewItem;
MessageBox.Show(clicked_parent.Header.ToString());
}
不要忘记添加错误检查,如果用户点击root,这将引发异常。