views:

387

answers:

1

How can I attach a click event on to a TreeViewItem?

The following works for the TextBlock but not the TreeViewItem:

XAML:

<Window x:Class="TestClickTree2343.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
        </Style>
    </Window.Resources>

    <StackPanel>
        <TextBlock Text="Click this" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"/>
        <TreeViewItem Header="Files">
            <TreeViewItem Header="File 1">
                <TreeViewItem Header="Part 1">
                    <TreeViewItem Header="Paragraph 1" MouseLeftButtonDown="TreeViewItem_MouseLeftButtonDown"/>
                    <TreeViewItem Header="Paragraph 2"/>
                </TreeViewItem>
            </TreeViewItem>
        </TreeViewItem>
    </StackPanel>
</Window>

Code-Behind:

using System.Windows;
using System.Windows.Input;

namespace TestClickTree2343
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void TreeViewItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("treeview item was clicked, this does NOT work");
        }

        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("textblock item was clicked, this WORKS");
        }
    }
}
+1  A: 

Trying using the PreviewMouseLeftButtonDown event rather than MouseLeftButtonDown.

Accoding to the MSDN docs both the PreviewMouseLeftButtonDown and MouseLeftButtonDown using a Direct routing strategy so I am not too sure why this is the case. However, it is possible that the documentation is incorrect, as generally 'Preview' events use the Tunneling strategy while their counterparts using the Bubble.

Richard C. McGuire
PreviewMouseLeftButtonDown works well, not sure what is blocked it either, good thing to remember, thanks.
Edward Tanguay