TreeViewItem事件通过父母冒泡

时间:2020-08-31 09:57:56

标签: c# wpf .net-core

我在运行时在TreeView中创建了一个简单的树。

enter image description here

每个TreeViewItem都有一个鼠标双击事件,该事件应打印出所单击项目的标题以及与该项目有关的一些信息。但是,如果双击6,则事件将在6触发,并在每个项目中冒泡。即使已将handle设置为true。


<Window x:Class="TreeBubbleIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TreeView Name="TestingTree" />
    </Grid>
</Window>
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Controls;

namespace TreeBubbleIssue
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            RunTimeGeneratedTree();
        }

        private void RunTimeGeneratedTree()
        {
            TreeViewItem first = new TreeViewItem { Header = 1 };

            string randomString = RandomString();

            first.MouseDoubleClick += (sender, args) =>
            {
                Debug.WriteLine($"{first.Header}: {randomString}");
                args.Handled = true;
            };

            TreeViewItem last = first;

            for (int i = 2; i <= 6; i++)
            {
                TreeViewItem item = new TreeViewItem { Header = i };
                string otherInfoFromElseWhere = RandomString();
                item.MouseDoubleClick += (sender, args) =>
                {
                    Debug.WriteLine($"{item.Header}: {otherInfoFromElseWhere}");
                    args.Handled = true;
                };

                last.Items.Add(item);
                last = item;
            }

            TestingTree.Items.Add(first);
        }

        private static readonly Random Random = new Random();

        public static string RandomString()
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, 50)
                .Select(s => s[Random.Next(s.Length)]).ToArray());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据MSDN论坛上的this issue,这是预期的行为。尽管您处理了该事件,但它仍然会冒泡。您可以尝试两种解决方法。

  • 在事件处理程序中检查SelectedItem
  • 选中OriginalSource并找到第一个父级TreeViewItem

由于第一个选项可能不适用于其他点击事件,因此我将向您展示第二个示例。

item.MouseDoubleClick += (sender, args) =>
{
   if (FindParent<TreeViewItem>((DependencyObject)args.OriginalSource) == args.Source)
      Debug.WriteLine($"{item.Header}: {otherInfoFromElseWhere}");
};
public static DependencyObject FindParent<T>(DependencyObject dependencyObject)
{
   while (dependencyObject != null && typeof(T) != dependencyObject.GetType())
      dependencyObject = VisualTreeHelper.GetParent(dependencyObject);

   return dependencyObject;
}