WPF: How to attach mouse events to a viewmodel?

后端 未结 6 1992
南笙
南笙 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:22

    I found a way to handle events raised by objects in the DataTemplate.

    (1) attach event handlers to the ItemsControl

    
    

    (2) to find out which item the event applies to, treat the OriginalSource as a FrameworkElement, and get its DataContext:

    void Node_DragStarted(object sender, DragStartedEventArgs e)
    {
        var os = (FrameworkElement)e.OriginalSource;
        var vm = os.DataContext as ItemViewModel;
        if (vm != null)
            // do something with the item ViewModel
    }
    

提交回复
热议问题