WPF: How to attach mouse events to a viewmodel?

后端 未结 6 1993
南笙
南笙 2021-02-04 19:47

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; th

6条回答
  •  孤街浪徒
    2021-02-04 20:07

    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:

    Grid grid = (Grid)_itemsControl.Template.FindName("Panel", _itemsControl);
    

    Then you attach event handlers to the grid, and inside the mouse event handlers, get the mouse coordinates w.r.t. the grid using

    Point p = e.GetPosition((IInputElement)sender);
    

    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.

提交回复
热议问题