WPF/MVVM - how to handle double-click on TreeViewItems in the ViewModel?

前端 未结 8 1899
刺人心
刺人心 2020-11-28 06:39

(Note - this is a re-post as my first question got posted under wrong headline: Here Sorry!)

I have a standard WPF treeview and have bound items to view model classe

8条回答
  •  庸人自扰
    2020-11-28 07:28

    Both Meleak and ígor's recommendations are great, but when the double click event handler is bound to TreeViewItem then this event handler is called for all of the item's parent elements (not just the clicked element). If it is not desired, here is another addition:

    private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
    {
        Control control = sender as Control;
        ICommand command = (ICommand)control.GetValue(CommandProperty);
        object commandParameter = control.GetValue(CommandParameterProperty);
    
        if (sender is TreeViewItem)
        {
            if (!((TreeViewItem)sender).IsSelected)
                return;
        }
    
        if (command.CanExecute(commandParameter))
        {
            command.Execute(commandParameter);
        }
    }
    

提交回复
热议问题