I am trying to use the MVVM pattern for the first time. So I have an ItemsControl filled with my viewmodel objects, displayed using DataTemplate‘s; the objects are “nodes” and “edges” represented in DataTemplate‘s with Thumb and Polyline objects and I want to be able to detect clicks and drags on the ItemsControl in order to move the nodes and edges.
Two questions:
- How do I attach mouse event handlers to the
Polyline‘s andThumb‘s to be handled by the little viewmodels? (I could attach aThumb.DragDeltahandler to theItemsControlande.OriginalSourcepoints to theThumb, but how do I get the corresponding viewmodel object?) - How do I attach mouse event handlers to the
ItemsControlto detect mouse clicks and drags on blank space? (answer is below)
Note: I know it might not be considered a proper ViewModel if it’s directly handling events of the View. But the important point is, I need to handle mouse events and I am not sure how to attach them.
I figured out the answer to the second question. I needed an ItemsControl that supported scrolling, and I needed to have the items on a Grid rather than the default StackPanel. To fulfill both requirements, I used a ControlTemplate:
In order to get mouse events with meaningful mouse coordinates (i.e. coordinates in scrollable space), it was necessary to obtain a reference to the grid using a strange incantation:
Then you attach event handlers to the grid, and inside the mouse event handlers, get the mouse coordinates w.r.t. the grid using
In order to get mouse events on the entire surface, the control (actually the grid) must have a background, so I set Background=”LightYellow” above, which propagates to the grid via a binding in the ControlTemplate.