New to Telerik UI for WPF? Download free 30-day trial

Select the clicked Item of a RadTreeView

This tutorial will show you how to select the item that was clicked, while opening the RadContextMenu. In order to achieve this, you have to do the following things:

  • Handle the Opened event of the RadContextMenu

  • Get an instance of the clicked RadTreeViewItem

  • Set the SelectedItem of the RadTreeView

Before starting, here is a sample RadTreeView with a sample RadContextMenu attached.

<telerik:RadTreeView x:Name="radTreeView"> 
    <telerik:RadContextMenu.ContextMenu> 
        <telerik:RadContextMenu x:Name="radContextMenu"> 
            <telerik:RadMenuItem Header="Menu Option 1" /> 
            <telerik:RadMenuItem Header="Menu Option 2" /> 
            <telerik:RadMenuItem Header="Menu Option 3" /> 
        </telerik:RadContextMenu> 
    </telerik:RadContextMenu.ContextMenu> 
    <telerik:RadTreeViewItem Header="Category1"> 
        <telerik:RadTreeViewItem Header="Product1" /> 
        <telerik:RadTreeViewItem Header="Product2" /> 
        <telerik:RadTreeViewItem Header="Product3" /> 
    </telerik:RadTreeViewItem> 
    <telerik:RadTreeViewItem Header="Category2" /> 
    <telerik:RadTreeViewItem Header="Category3" /> 
    <telerik:RadTreeViewItem Header="Category4"> 
        <telerik:RadTreeViewItem Header="Product A" /> 
        <telerik:RadTreeViewItem Header="Product B" /> 
        <telerik:RadTreeViewItem Header="Product C" /> 
    </telerik:RadTreeViewItem> 
    <telerik:RadTreeViewItem Header="Category5" /> 
</telerik:RadTreeView> 

To handle the Opened event attach an event handler to it.

<telerik:RadContextMenu x:Name="radContextMenu1"  
                        Opened="RadContextMenu_Opened"> 
    <telerik:RadMenuItem Header="Menu Option 1" /> 
    <telerik:RadMenuItem Header="Menu Option 2" /> 
    <telerik:RadMenuItem Header="Menu Option 3" /> 
</telerik:RadContextMenu> 

private void RadContextMenu_Opened( object sender, RoutedEventArgs e ) 
{ 
} 

In it get the instance of the clicked RadTreeViewItem by calling the GetClickedElement<T>() method of the RadContextMenu.

private void RadContextMenu_Opened(object sender, RoutedEventArgs e) 
{ 
    RadTreeViewItem item = this.radContextMenu.GetClickedElement<RadTreeViewItem>(); 
} 

The last thing to do is to set the SelectedItem property of the RadTreeView to the instance of the RadTreeView item that has been clicked.

If you are having a dynamic data scenario, where the RadTreeView is bound to a collection, you have to set the SelectedItem property to the DataContext of the clicked RadTreeViewItem.

private void RadContextMenu_Opened(object sender, RoutedEventArgs e) 
{ 
    RadTreeViewItem item = this.radContextMenu.GetClickedElement<RadTreeViewItem>(); 
    if (item != null) 
    { 
        this.radTreeView.SelectedItem = item; 
    } 
}