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

前端 未结 8 1916
刺人心
刺人心 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:20

    Just for curiosity: what if I take Frederiks part, but implement it directly as behavior?

    public class MouseDoubleClickBehavior : Behavior
    {
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof (ICommand), typeof (MouseDoubleClickBehavior), new PropertyMetadata(default(ICommand)));
    
        public ICommand Command
        {
            get { return (ICommand) GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
    
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof (object), typeof (MouseDoubleClickBehavior), new PropertyMetadata(default(object)));
    
        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
    
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.MouseDoubleClick += OnMouseDoubleClick;
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.MouseDoubleClick -= OnMouseDoubleClick;
            base.OnDetaching();
        }
    
        void OnMouseDoubleClick(object sender, RoutedEventArgs e)
        {
            if (Command == null) return;
            Command.Execute(/*commandParameter*/null);
        }
    }
    

提交回复
热议问题