简体   繁体   中英

Updating treeview control in WPF

In my application as soon as an object is dropped on canvas I stored it in a tree. Now, I'm trying to write a method to delete an object which is fine but I also need to delete that specific object from the tree. Each object has a unique id so this way I can find it in tree and remove it from tree while being deleted from the canvas.

In order to find a node in tree I have planned to store ID in each node (item.Tag), however, I'm facing two problems:

  1. How can I access to details of a node from a different class? myTreeObj.Items.Tag doesn't work properly.

  2. When I loop in tree myTreeObj.Items.Count shows more items that what I see.

Any comments will be appreciated.

Thanks.

In WPF, TreeViews are actually what they say they are: a view of a data structure. In WinForms, you had to crawl up and down the nodes of a TreeView and add them or remove them manually. In WPF, the proper approach is to add or remove items from the actual data hierarchy (to which the TreeView is binding) and use PropertyChanged or CollectionChanged notifications to tell the TreeView to update itself automatically.

What you are trying to do may be possible, but it is going to be an uphill fight all the way, and things will not work as expected. WPF REALLY wants you to use databinding, and any other approach is going to give you headaches.

This article may be a helpful place to start understanding how to work with the WPF TreeView: http://joshsmithonwpf.wordpress.com/2008/05/24/the-wpf-treeview-is-a-view-of-a-tree/

EDIT: The author's original article is actually more helpful: http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM