Get logical path from treeview which has HierarchicalDataTemplate
I have a structure of geography objects:
Country
Areas,
Provinces,
Cities
and Hotels
Coun开发者_如何转开发try has areas, areas has provinces, provinces has cities, and cities has hotels. Whne I'll click City node I wanna to get logical path eg: France,Provanse,SomeProvince,Montpellier,Grand Hotel.
Each class has fields: name, code nad listOf...
Treeview works great, but this method not:
private void structureTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (structureTree.SelectedItem is Hotel)
{
objectCode = ((Hotel)structureTree.SelectedItem).Code;
TreeViewItem item = e.OriginalSource as TreeViewItem;
DependencyObject parent = VisualTreeHelper.GetParent(item);
dlgEditHotel(objectCode, structureTree.Parent.ToString());
}
}
`**structureTree.SelectedItem as TreeViewItem **`
gives me null, when I'll click at some area, province,city or hotel
you could store names of tree items in their Tag or somewhere, and at SelectedItemChanged recursively traverse the tree up to the topmost item and build up the pathstring.
you can read DataContext property of each TreeviewItem and will get the item(Country, Areas, Provinces, Cities, etc.). Read the Name(for example) and append into the path string recursively while traversing through the tree.
I have created a treeview as follows:
<TreeView Name="tree">
<TreeViewItem Header="Country" Selected="GetName">
<TreeViewItem Header="Areas" Selected="GetName">
<TreeViewItem Header="Provinces" Selected="GetName">
<TreeViewItem Header="Cities" Selected="GetName">
<TreeViewItem Header="Hotels" Selected="GetName">
</TreeViewItem>
</TreeViewItem>
</TreeViewItem>
</TreeViewItem>
</TreeViewItem>
</TreeView>
Now GetName method would do something like this:
private void GetName(object sender, RoutedEventArgs e)
{
TreeViewItem item = (TreeViewItem)sender;
name = item.Header + "." + name;
if (!(item.Parent is TreeViewItem))
{
MessageBox.Show(name);
}
}
In the end the MessageBox would Show name as
Country.Areas.Provinces.Cities.Hotels.
I hope this is what you wanted.
精彩评论