How do I make the TreeViewItem(s) of an existing WPF TreeView raise a Click event?
Currently, we are handling the SelectedItemChanged. In our case, we are displaying dialogs, so the user may click on the same selected TreeViewItem multiple times.
How do I make the TreeViewItem(s) of an existing WPF TreeView raise a Click event?
Currently, we are handling the SelectedItemChanged. In our case, we are displaying dialogs, so the user may click on the same selected TreeViewItem multiple times.
<Window x:Class="MenuExperiment1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<TreeView Name="treeView1"
Height="320"
Width="200">
<TreeView.Resources>
<Style TargetType="TreeViewItem">
<EventSetter Event="MouseLeftButtonUp"
Handler="treeViewItem_MouseLeftButtonUp" />
<EventSetter Event="KeyUp"
Handler="treeViewItem_KeyUp" />
</Style>
</TreeView.Resources>
<TreeViewItem Header="aa" />
<TreeViewItem Header="bb">
<TreeViewItem Header="b1"></TreeViewItem>
<TreeViewItem Header="b2"></TreeViewItem>
</TreeViewItem>
<TreeViewItem Header="cc">
<TreeViewItem Header="c1">
<TreeViewItem Header="c1a"></TreeViewItem>
<TreeViewItem Header="c1b"></TreeViewItem>
</TreeViewItem>
<TreeViewItem Header="c2"></TreeViewItem>
</TreeViewItem>
<TreeViewItem Header="dd" />
</TreeView>
</Window>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Diagnostics;
namespace MenuExperiment1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void treeViewItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Handler(sender,e);
}
private void treeViewItem_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Handler(sender, e);
}
}
private void Handler(object sender, InputEventArgs e)
{
e.Handled = true;
Debug.Write(((TreeViewItem)sender).Header);
Debug.WriteLine(" clicked");
}
}
}
Have you tried using the MouseLeftButtonUp event? You should be able to achieve the same UX by hooking to that event as you would with an actual click event.
PreviewMouseLeftButtonDown and MouseLeftButtonDown may also work for you depending on the layout of your TreeViewItems (such as using a content template containing a TextBlock for example).