如何使现有WPF TreeView的TreeViewItem引发Click事件?
目前,我们正在处理SelectedItemChanged。在我们的例子中,我们正在显示对话框,因此用户可以多次单击相同的选定TreeViewItem。
答案 0 :(得分:1)
<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");
}
}
}
答案 1 :(得分:0)
您是否尝试过使用MouseLeftButtonUp事件?您应该能够像实际点击事件一样通过挂钩到该事件来实现相同的UX。
PreviewMouseLeftButtonDown和MouseLeftButtonDown也可能适合您,具体取决于TreeViewItems的布局(例如,使用包含TextBlock的内容模板)。
答案 2 :(得分:0)
您可以在ItemContainerStyle
的{{1}}中使用事件设定器:
TreeView