如何将Click事件附加到TreeViewItem上?
以下适用于TextBlock但不适用于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>
代码隐藏:
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");
}
}
}
答案 0 :(得分:4)
尝试使用PreviewMouseLeftButtonDown事件而不是MouseLeftButtonDown。
使用直接路由策略向MSDN文档同时使用PreviewMouseLeftButtonDown和MouseLeftButtonDown,因此我不太清楚为什么会出现这种情况。但是,文档可能不正确,因为通常“预览”事件使用隧道策略,而使用冒泡的对应物则使用。
答案 1 :(得分:0)
上述解决方案有效但在单击父节点时会阻止展开树视图节点。
此致