WPF TreeView 项目被点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16584627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:48:27  来源:igfitidea点击:

WPF TreeView item clicked

wpfeventsclicktreeview

提问by Weixiang Guan

I am a problem with the event in WPF. Say I have a underlying data model and a tree view to present the data. The simplest thing I want to do is, when I click on one item, I would do something with underlying data associated with that item.

我对 WPF 中的事件有疑问。假设我有一个底层数据模型和一个树视图来呈现数据。我想要做的最简单的事情是,当我点击一个项目时,我会对与该项目相关联的基础数据做一些事情。

I tried using the MouseLeftButtonDownevent of the Textblock, but then the sender object is just the Textblockitself and I cannot get access to the underlying data.

我尝试使用 的MouseLeftButtonDown事件Textblock,但是发件人对象只是它Textblock本身,我无法访问基础数据。

Now I also tried using the MouseLeftButtonDownevent of the TreeViewItemlike this:

现在我也尝试使用这样的MouseLeftButtonDown事件TreeViewItem

<TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
         <EventSetter Event="MouseLeftButtonDown" Handler="itemClicked"/>
    </Style>
</TreeView.ItemContainerStyle>

But I did not get the handler called.

但是我没有得到处理程序的调用。

So how exactly should I do this? Is there some kind of standard approach?

那么我到底应该怎么做呢?是否有某种标准方法?

回答by makc

The MouseLeftButtonDown event is a bubbling event it got handled somewhere in its route my guess Selector. You can use snoop to see who handled the event. Using PreviewMouseLeftButtonDown/SelectedItemChanged or in your case MouseDoubleClick will solve the problem.

MouseLeftButtonDown 事件是一个冒泡事件,它在我猜测的选择器路径中的某处得到处理。您可以使用 snoop 来查看谁处理了事件。使用 PreviewMouseLeftButtonDown/SelectedItemChanged 或在您的情况下 MouseDoubleClick 将解决问题。

<TreeView>
  <TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
        <EventSetter Event="MouseDoubleClick"
                Handler="itemDoubleClicked"/>
    </Style>
  </TreeView.ItemContainerStyle>
</TreeView>