views:

80

answers:

2

I want every clickable TreeViewItem to execute TreeViewItem_MouseLeftButtonDown, is there a way to put this in the style so I don't have to define it everywhere. I could run through all children in code behind but I would think there would be an easier way to do it in a style.

The following code gives me:

Cannot find the Style Property 'PreviewMouseLeftButtonDown' on the type 'System.Windows.Controls.TreeViewItem'.

<Window x:Class="TestClickTree2343.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    WindowStartupLocation="CenterScreen"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
            <Setter Property="Foreground" Value="#aaa" />
        </Style>
        <Style x:Key="TreeViewItemClickableStyle" TargetType="TreeViewItem">
            <Setter Property="Cursor" Value="Hand" />
            <Setter Property="Foreground" Value="#000" />
            <Setter Property="PreviewMouseLeftButtonDown" Value="TreeViewItem_MouseLeftButtonDown" />
        </Style>
    </Window.Resources>

    <StackPanel>
        <TreeViewItem Header="Files">
            <TreeViewItem Header="File 1">
                <TreeViewItem Header="Part 1">
                    <TreeViewItem Style="{StaticResource TreeViewItemClickableStyle}" Header="Paragraph 1"/>
                    <TreeViewItem Header="Paragraph 2"/>
                </TreeViewItem>
            </TreeViewItem>
        </TreeViewItem>
    </StackPanel>
</Window>
A: 

Use SelectedItemChanged in TreeView instead:

XAML:

<TreeView  SelectedItemChanged="TreeView_SelectedItemChanged" BorderThickness="0">
    <TreeViewItem 
        Tag="File1" 
        Style="{StaticResource TreeViewItemClickableStyle}" 
        Header="File 1">

        <TreeViewItem Header="Part 1">

            <TreeViewItem Header="Paragraph 1"/>

            <TreeViewItem 
                Tag="Paragraph1" 
                Style="{StaticResource TreeViewItemClickableStyle}" 
                Header="Paragraph 2"/>

            <TreeViewItem Header="Paragraph 3"/>
            <TreeViewItem Header="Paragraph 4"/>
            <TreeViewItem Header="Paragraph 5"/>

        </TreeViewItem>
    </TreeViewItem>
</TreeView>

Code-behind:

private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    TreeViewItem treeViewItem = ((TreeView)sender).SelectedItem as TreeViewItem;
    if (treeViewItem.Tag != null)
    {
        string tag = treeViewItem.Tag.ToString();
        MessageBox.Show(String.Format("You clicked the tree item: {0}", tag));
    }
}
Edward Tanguay
A: 

Can we select using right click..

asit