如何防止 WPF TreeView 在多个项目上引发 MouseEnter?
我有以下应该创建一棵树的代码片段。该树的每个项目在悬停时都应更改其背景。
XAML:
<TreeView Name="treeView">
<TreeViewItem Header="Item 1" IsExpanded="True">
<TreeViewItem Header="Item 1.1" IsExpanded="True">
<TreeViewItem Header="Item 1.1.1"/>
<TreeViewItem Header="Item 1.1.1"/>
</TreeViewItem>
<TreeViewItem Header="Item 1.2"/>
</TreeViewItem>
</TreeView>
C# 代码隐藏:
class MainWindow : Window
{
// ...
private void SetEventHandlersOn(ItemCollection items)
{
foreach (TreeViewItem item in items)
{
item.MouseEnter += ItemMouseEnter;
item.MouseLeave += ItemMouseLeave;
SetEventHandlersOn(item.Items);
}
}
private void ItemMouseEnter(object sender, MouseEventArgs e)
{
var treeViewItem = sender as TreeViewItem;
treeViewItem.Background = Brushes.LimeGreen;
e.Handled = true;
}
private void ItemMouseLeave(object sender, MouseEventArgs e)
{
var treeViewItem = sender as TreeViewItem;
treeViewItem.Background = Brushes.White;
e.Handled = true;
}
}
树没有执行我需要的操作,而是以不同的方式显示。 当我悬停某个项目时,它会突出显示,但由于某种原因,其父项也会突出显示。
我该如何解决该问题?
UPD1 我发现我的问题与描述的问题非常相似 此处但我还不明白如何应用该解决方案。
I have the following pieces of code which should create a tree. Each item of that tree should change its background when it is hovered.
XAML:
<TreeView Name="treeView">
<TreeViewItem Header="Item 1" IsExpanded="True">
<TreeViewItem Header="Item 1.1" IsExpanded="True">
<TreeViewItem Header="Item 1.1.1"/>
<TreeViewItem Header="Item 1.1.1"/>
</TreeViewItem>
<TreeViewItem Header="Item 1.2"/>
</TreeViewItem>
</TreeView>
C# Code behind:
class MainWindow : Window
{
// ...
private void SetEventHandlersOn(ItemCollection items)
{
foreach (TreeViewItem item in items)
{
item.MouseEnter += ItemMouseEnter;
item.MouseLeave += ItemMouseLeave;
SetEventHandlersOn(item.Items);
}
}
private void ItemMouseEnter(object sender, MouseEventArgs e)
{
var treeViewItem = sender as TreeViewItem;
treeViewItem.Background = Brushes.LimeGreen;
e.Handled = true;
}
private void ItemMouseLeave(object sender, MouseEventArgs e)
{
var treeViewItem = sender as TreeViewItem;
treeViewItem.Background = Brushes.White;
e.Handled = true;
}
}
Instead of doing what I need the tree appears differently. When I hover an item, it becomes highlighted, but its parent items are also highlighted for some reason.
How can I solve the problem?
UPD1 I see that my problem is very similar to the problem described here but I haven't understood yet how to apply the solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该像这样检查处理程序中的 e.Handled 状态:
那么它只会被处理一次。
you should check for e.Handled state in your handler like this:
then it will be handled only once.