2014-03-27 79 views
0

我只想從TreeView中訪問選定子元素的父元素。這是一個WPF應用程序,我需要的C#代碼來獲得所選擇的孩子和父母,作爲strings.The功能是:從WPF的TreeView中讀取父元素

private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) 
{ 

//How to get the selected child and parents as strings 

} 

回答

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()); 

    } 

不要忘記添加錯誤檢查,如果用戶點擊根,這將引發異常。