Note that there are some explanatory texts on larger screens.

plurals
  1. POIn WPF, how do I select the treeview item under my cursor on right-click?
    primarykey
    data
    text
    <p>In WPF, when I right-click on a treeview item I would like it to be Selected/Activated before showing the context menu.</p> <p>This sounds pretty simple, but the inclusion of a hierachicalDataTemplate complicates things a little.</p> <p>I have the following treeview:</p> <pre><code>&lt;TreeView x:Name="trv" ContextMenu="{StaticResource contextMenu}" ItemTemplate="{StaticResource treeHierarchicalDataTemplate}" ItemsSource="{Binding Source={StaticResource meetingItems}}" &gt; &lt;TreeView.ItemContainerStyle&gt; &lt;Style TargetType="{x:Type TreeViewItem}"&gt; &lt;EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="trv_PreviewMouseRightButtonDown"/&gt; &lt;Setter Property="IsExpanded" Value="True"&gt;&lt;/Setter&gt; &lt;/Style&gt; &lt;/TreeView.ItemContainerStyle&gt; &lt;/TreeView&gt; </code></pre> <p>And here is my event handler...</p> <pre><code>private void trv_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { TreeViewItem item = sender as TreeViewItem; if (item != null) { item.Focus(); e.Handled = true; } } </code></pre> <p>Note how I add an EventSetter above. This ALMOST works. But it only selects the root-level treeview node (i.e. the root parent of the node on which I right click). This may be because of my hierarchical data template? This template can contain children OF THE SAME TYPE.</p> <p>Here is my hierarchical data template...</p> <pre><code>&lt;HierarchicalDataTemplate x:Key="treeHierarchicalDataTemplate" ItemsSource="{Binding Path=ChildMeetingItems}"&gt; &lt;HierarchicalDataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding Path=Red}" Value="True"&gt; &lt;Setter TargetName="img" Property="Image.Source" Value="pack://siteoforigin:,,,/images/bookRed.png"&gt;&lt;/Setter&gt; &lt;/DataTrigger&gt; &lt;/HierarchicalDataTemplate.Triggers&gt; &lt;StackPanel x:Name="treeViewItemPanel" Background="Transparent" Orientation="Horizontal"&gt; &lt;Image Width="16" Height="16" x:Name="img" Margin="0,0,4,0" Source="pack://siteoforigin:,,,/images/bookGreen.png"&gt;&lt;/Image&gt; &lt;TextBlock Foreground="DarkGray" Text="{Binding DisplayIndex}" Margin="0,0,5,0"&gt;&lt;/TextBlock&gt; &lt;TextBlock Text="{Binding Summary}"&gt;&lt;/TextBlock&gt; &lt;/StackPanel&gt; &lt;/HierarchicalDataTemplate&gt; </code></pre> <p>Any idea on why only the root node instead of child nodes are selected when I right-click?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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