WPF selection of a TreeView item as context menu is called

前端 未结 3 1367
别那么骄傲
别那么骄傲 2020-12-21 11:06

This problem relates mainly to context menus, but in my specific case it\'s about a TreeView control.

The TreeView item contains a StackPanel, and on that StackPanel

3条回答
  •  春和景丽
    2020-12-21 11:28

    You can use a behavior for it:

    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Interactivity;
    
    public class SelectOnRMBBehavior : Behavior
    {
        public static readonly DependencyProperty CurrentItemProperty = DependencyProperty.Register("CurrentItem", typeof(TreeViewItem), typeof(SelectOnRMBBehavior), new PropertyMetadata(null));
    
        public TreeViewItem CurrentItem
        {
            get
            {
                return (TreeViewItem)GetValue(CurrentItemProperty);
            }
            set
            {
                SetValue(CurrentItemProperty, value);
            }
        }
    
        protected override void OnAttached()
        {
            base.OnAttached();
    
            AssociatedObject.PreviewMouseRightButtonDown += AssociatedObject_PreviewMouseRightButtonDown;
        }
    
        private void AssociatedObject_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (CurrentItem!=null)
            {
                CurrentItem.IsSelected = true;
            }
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.PreviewMouseRightButtonDown -= AssociatedObject_PreviewMouseRightButtonDown;
    
            base.OnDetaching();
        }
    }
    

    and then just put your behavior to the element which will be clicked(I suppose a container in DataTemplate):

    
        
            
        
    
    

提交回复
热议问题