Schlurb
Schlurb

Reputation: 25

How to get parent of Tree(List)View Item?

i'm currently working on a project which shall display some date in a hierarchical way. I'm using a Tree(List)View (the one from Ricciolo) which has 3 hierarchical levels. The ItemsSource of the TLV is a List.

1st level = typeof(Game)
2nd level = typeof(Partner)
3rd level = typeof(Channel)

Everything is being displayed fine but now I have a problem. I want to start an edit mode for selected items, but therefore it is necessary to find out if and which parents the selected item has. I already tried the following approach:

TreeViewItem myItem = e.OriginalSource as TreeViewItem;
if ( myItem != null ) {
    ItemsControl parent = ItemsControl.ItemsControlFromItemContainer( myItem );
    if ( parent != null ) {
    //Put your logic here.
    }
}

The problem here is, no matter which item I select, "myItem" will always be null.

Can somebody please point me into the right direction ?

Thx in advance, Greetings

Upvotes: 1

Views: 2116

Answers (4)

Manish
Manish

Reputation: 510

Try to get the parent using VisualTreeHelper.

Upvotes: 0

ChrisWue
ChrisWue

Reputation: 19070

Depending on which event you handle (MouseButtonDown?) the e.OriginalSource very likely contains the control within the TreeViewItem which raised the event (probably a TextBlock). You might have to walk up the VisualTree a bit using the VisualTreeHelper to find the enclosing container (TreeViewItem).

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174467

You really should be using the MVVM pattern in your application. See this article for a good introduction, specifically in the case of tree views.

Currently, codeproject seems to have a problem. You can access the article in the google cache

Upvotes: 2

brunnerh
brunnerh

Reputation: 185553

You use a safe-cast using as so e.OriginalSource is not a TreeViewItem, set a breakpoint and use the debugger and see what it is.

Upvotes: 0

Related Questions