WPF TreeView,在PreviewMouseDown事件中获取TreeViewItem

时间:2010-05-31 06:31:50

标签: wpf treeview mouseevent

如何确定在PreviewMouseDown事件中单击的TreeViewItem?

2 个答案:

答案 0 :(得分:8)

以下似乎有效:

private void myTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
  TreeViewItem item = GetTreeViewItemClicked((FrameworkElement)e.OriginalSource, 
                                                                       myTreeView);
  ...
}

private TreeViewItem GetTreeViewItemClicked(FrameworkElement sender, TreeView treeView)
{
  Point p = ((sender as FrameworkElement)).TranslatePoint(new Point(0, 0), treeView);
  DependencyObject obj = treeView.InputHitTest(p) as DependencyObject;
  while (obj != null && !(obj is TreeViewItem))
    obj = VisualTreeHelper.GetParent(obj);
  return obj as TreeViewItem;
}

答案 1 :(得分:2)

我最初在TreeView上使用了一个扩展方法,它接受了一个UIElement-- PreviewMouseDown事件的发送者 - 就像这样:

private void MyTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var uiElement = sender as UIElement;
    var treeViewItem = myTreeView.TreeViewItemFromChild(uiElement);
}

这是扩展方法(如果您直接在TreeViewItem上单击,它会检查子项本身)...

public static TreeViewItem TreeViewItemFromChild(this TreeView treeView, UIElement child)
{
    UIElement proposedElement = child;

    while ((proposedElement != null) && !(proposedElement is TreeViewItem))
        proposedElement = VisualTreeHelper.GetParent(proposedElement) as UIElement;

    return proposedElement as TreeViewItem;
}

更新

但是,我已经把它改成了一个我可以在任何地方使用的更通用的版本。

public static TAncestor FindAncestor<TAncestor>(this UIElement uiElement)
{
    while ((uiElement != null) && !(uiElement is TAncestor))
        retVal = VisualTreeHelper.GetParent(uiElement) as UIElement;

    return uiElement as TAncestor;
}

找到你正在寻找的类型(再次,包括检查自己)或返回null

您可以在同一个PreviewMouseDown处理程序中使用它,如此...

private void MyTreeView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var uiElement = sender as UIElement;
    var treeViewItem = uiElement.FindAncestor<TreeViewItem>();
}

当我的TreeViewItem在其模板中有一个CheckBox并且我想在用户点击通常吞下事件的复选框时选择该项时,这非常方便。

希望这有帮助!