Amit Dey from Microsoft contributed a nice Silverlight code sample that demonstrates enabling CRUD (Create, Read, Update, Delete) and drag & drop in Silverlight TreeView control. Silverlight TreeView control with CRUD and drag & drop is a frequently asked programming question in Silverlight forums. Many customers also requested this code sample in our code sample request service. We hope that this sample can reduce developers' efforts in handling this typical programming scenario.
This is a code sample for a Silverlight TreeView Control which supports CRUD ( Create, Read, Update, Delete ) operations. In addition it supports Drag & Drop of items. This post assumes that you have atleast a nodding acquaintance with Silverlight and Data Binding. Our final output will look something like this. Data
First lets us have a look at the data structure which is bound to the TreeView control. Node is the class, whose instance is bound to each TreeViewItem. Text represents the data at a node. Children represents the childs of a node. Notice that the Node inherits System.ComponentModel.INotifyPropertyChanged class inorder to keep the UI in sync. Read this article to better understand this functionality.
Also notice the hepler functions Add and Delete which add and delete a child node respectively
Now let us see the XAML definition for the user control.
First thing, I have implemented a Context Menu to facilitate CRUD operations. You can read this blog to learn how one can be implemented.
Next, notice the two HierarchicalDataTemplate. One is for the TreeViewItem in Read Mode ( hence a TextBlock ) and the other in Edit mode ( hence a TextBox ). The TextBox and the TextBlock are bound to the Text property of the Node.
I am using the TreeViewDragDropTarget control from Silverlight Toolkit to enable Drag-And-Drop of TreeViewItems among parent nodes.
Now let us have a sneak peek at the code behind for our UserControl.
First, the Mouse Event Handlers. The MouseRightButtonUp event for a TreeViewItem does two things. It assigns that particular TreeViewItem’s Data Context as the selectedNode. Second, it shows up the ContextMenu. The selectedNode information is necessary as that is used as a reference to Edit the TreeViewItem, Add Children to the TreeViewItem or delete the TreeViewItem.
The AddButton_Click event handler, creates a new Node and adds it as a children of the selecteNode.
The EditButton_Click event handler, changes the Template of the selected TreeViewItem to Edit mode.
The DeleteButton_Click event handler, first identifies the TreeViewItem associated with the selectedNode, finds its parent, and deletes the selectedNode from the Parent.