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
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):