Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could define a <code>DependencyProperty</code>. Below I have shared a sample app which uses a dependency property to achieve this. </p> <p>TreeViewExtension.cs</p> <pre><code>using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace WpfApplication1 { public static class TreeViewExtension { public static readonly DependencyProperty SelectItemOnRightClickProperty = DependencyProperty.RegisterAttached( "SelectItemOnRightClick", typeof(bool), typeof(TreeViewExtension), new UIPropertyMetadata(false, OnSelectItemOnRightClickChanged)); public static bool GetSelectItemOnRightClick(DependencyObject d) { return (bool)d.GetValue(SelectItemOnRightClickProperty); } public static void SetSelectItemOnRightClick(DependencyObject d, bool value) { d.SetValue(SelectItemOnRightClickProperty, value); } private static void OnSelectItemOnRightClickChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { bool selectItemOnRightClick = (bool)e.NewValue; TreeView treeView = d as TreeView; if (treeView != null) { if (selectItemOnRightClick) treeView.PreviewMouseRightButtonDown += OnPreviewMouseRightButtonDown; else treeView.PreviewMouseRightButtonDown -= OnPreviewMouseRightButtonDown; } } private static void OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { TreeViewItem treeViewItem = VisualUpwardSearch(e.OriginalSource as DependencyObject); if (treeViewItem != null) { treeViewItem.Focus(); e.Handled = true; } } public static TreeViewItem VisualUpwardSearch(DependencyObject source) { while (source != null &amp;&amp; !(source is TreeViewItem)) source = VisualTreeHelper.GetParent(source); return source as TreeViewItem; } } } </code></pre> <p>XAML:</p> <pre><code>&lt;Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mvvmhelper="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"&gt; &lt;Grid&gt; &lt;TreeView mvvmhelper:TreeViewExtension.SelectItemOnRightClick="true"&gt; &lt;TreeViewItem Header="One"/&gt; &lt;TreeViewItem Header="Two"/&gt; &lt;TreeViewItem Header="Three"/&gt; &lt;TreeView.ContextMenu&gt; &lt;ContextMenu&gt; &lt;MenuItem Header="Menu1"/&gt; &lt;MenuItem Header="Menu2"/&gt; &lt;/ContextMenu&gt; &lt;/TreeView.ContextMenu&gt; &lt;/TreeView&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload