WPF中Treeview控件子项的双击事件问题

5ssjco0h  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(196)

双击wpf中treeview控件的子项后Expanded或MouseDoubleClick会执行两次TreeViewItem_MouseDoubleClick或TreeViewItem_Expanded如何解决我双击子项时执行两次的问题

`<TreeView
         x:Name="Tree_Channel"
         ItemsSource="{Binding TreeItems}">
        <TreeView.ItemContainerStyle>
         <Style TargetType="{x:Type TreeViewItem}">
         <EventSetter Event="Expanded" Handler="TreeViewItem_Expanded" />
         <EventSetter Event="PreviewMouseDoubleClick"  Handler="TreeViewItem_MouseDoubleClick"/>
            </Style>
        </TreeView.ItemContainerStyle>
        <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
        <TextBlock Text="{Binding Name}" />
         </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

  public Window1()
        {
     InitializeComponent();
    DataContext = this;

        TreeItems = new ObservableCollection<TreeNode>();

        var rootNode1 = new TreeNode("Root 1");
        var rootNode2 = new TreeNode("Root 2");     
        rootNode1.Children.Add(new TreeNode("Child 1"));
        rootNode1.Children.Add(new TreeNode("Child 2"));
        rootNode2.Children.Add(new TreeNode("Child 3"));
        rootNode2.Children.Add(new TreeNode("Child 4"));     
        TreeItems.Add(rootNode1);
        TreeItems.Add(rootNode2);
    }
    public ObservableCollection<TreeNode> TreeItems { get; set; }
    private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
    {

    }  
    public class TreeNode

    {
        public string Name { get; set; }
        public ObservableCollection<TreeNode> Children { get; set; }

        public TreeNode(string name)
        {
            Name = name;
            Children = new ObservableCollection<TreeNode>();
        }
    }

    private void TreeViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {

    }
    }

字符串

jckbn6z7

jckbn6z71#

您遇到问题是父项也处理鼠标双击。您可以在处理程序中过滤它。

private void TreeViewItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    //Return, if parent item handler
    if (sender != e.OriginalSource)
    {
        TreeViewItem tvi = null;

        var visParent = VisualTreeHelper.GetParent(e.OriginalSource as FrameworkElement);
        while (tvi == null && visParent != null)
        {
            tvi = visParent as TreeViewItem;
            visParent = VisualTreeHelper.GetParent(visParent);
        }
        if (tvi == null || tvi != sender)                    
        {
            return; 
        }
    }

    e.Handled = true; // Stop expand behavior on double click
}

字符串

相关问题