Presenting Presentation

Published on 10/23/2013

I'm messing around with WPF and plumbing the XAML depths these days.

Creating Windows forms interfaces used be something I enjoyed immensely back in the day. Now with WPF it's a different ball game, but the challenge remains the same. Recently I'm been struggling with a hierarchically-bound tree view, and dragging and dropping within the same tree view as well as from outside.

Here's a list of the most tricky bits:

  • Once you initiate the action with DragDrop.DoDragDrop(), it doesn't exit until you drop.
  • Once you have dropped, finding on what you dropped is particularly difficult.
The result of the first point is that no mouse events are forthcoming during the drag operation, so you cannot keep track of the mouse over your tree view to determine the location with InputHitTest(). And even if you could, finding the correct destination is tricky. Using a combination of FrameworkElement, UIElement and the VisualTreeHelper resulted in inconsistent results: sometimes it's a border, other times a textblock. And the value of the attached DataContext is also pretty shaky.

My solution at the end of the day was to hook up the mouse, drag and drop events onto the tree view item HierarchicalDataTemplate static resources directly. This way, the source and destination of my drag operation was always related directly to the sender parameter.

Whilst keeping the event handlers on the tree view itself too, and setting the e.handled parameter correctly, the context of the drop action is exceptionally well defined. If the user drops on one of the tree items the template events will handle it where possible, else it will bubble back up to the tree view itself, where the context of dropping changes, and the item is added or linked differently. And at the same time the case of dropping onto the blank area of the tree is also handled. This works pretty well, and the remaining challenge is managing the data integrity in the background for consistent storage.

So until I've got my project page set up, I'll post a bit about my challenges on the news feed for now. It's not like there's any actual newsworthy events happening here at helloserve Productions anyway :)