tags:

views:

590

answers:

1

I'm searching for a linq-to-objects way to get a TreeViewItem from a treeView.

I want to do something like this:

var node =
            from TreeViewItem childs in tree.Items
            where  ((int) childs.Tag) == 1000   
            select childs;


string tag = ((TreeViewItem)node).Tag.ToString();

Then I want to append children to this node.

Thanks.

+1  A: 

You'll want to use FirstOrDefault to extract the first matching element from the enumeration created by the query. After checking that it's not null, you can then operate on it like you normally would.

 var query =
        from TreeViewItem childs in tree.Items
        where  ((int) childs.Tag) == 1000   
        select childs;

 var node = query.FirstOrDefault();

 if (node != null)
 {
    ...
 }

Note that you won't need the cast any longer since FirstOrDefault will return a TreeViewItem.

tvanfosson
Thank a lot! Tested and working.I had also to change the 'where clause':where Int32.Parse(childs.Tag.ToString()) == rw.PARENT_ID
Jonathan