TreeView double click event

11,195

Change your double click handler like shown below. Instead of calling ToString it accesses the Title property of your MenuItem item class.

private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
    var menuItem = trvMenu.SelectedItem as MyProject.MenuItem;

    if (menuItem != null)
    {
        MessageBox.Show(menuItem.Title);
    }
}
Share:
11,195
Yona
Author by

Yona

Updated on June 04, 2022

Comments

  • Yona
    Yona almost 2 years

    I want to define a double click even on a TreeView so that I will be able to know which item in the TreeView was selected and to get his title. The way I try to get it's title gets me "MyProject.MenuItem". How can I refer to the selected item on the tree, make sure it's not the root, and get it's title? What I did:

    <TreeView Name="trvMenu" HorizontalAlignment="Left" Height="312" VerticalAlignment="Top" Width="200" MouseDoubleClick="TreeView_MouseDoubleClick" >
            <TreeView.ItemTemplate>
                   <HierarchicalDataTemplate DataType="{x:Type local:MenuItem}" ItemsSource="{Binding Items}">
                         <TextBlock Text="{Binding Title}" />
                   </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
    </TreeView>
    

    The MessageBox shows "MyProject.MenuItem", what I want to do is not show a messagebox, but to get the title of the selected treeview item, after checking it is not the root

    private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            if (sender is TreeViewItem)
                if (!((TreeViewItem)sender).IsSelected)
                    return;
            TreeViewItem tviSender = sender as TreeViewItem;
            MessageBox.Show(trvMenu.SelectedItem.ToString());
        }
    
  • Yona
    Yona almost 10 years
    It doesn't recognize "Title" and doesn't give in to any casting >_<
  • Yona
    Yona almost 10 years
    ok, i did " MessageBox.Show(((MenuItem)trvMenu.SelectedItem).Title); " but now it doesn't even show the messagebox..
  • Krishna
    Krishna almost 10 years
    Just put a breakpoint on MessaBox.Show line and inspect trvMenu.SelectedItem and make sure that it the object that you are expecting it to be