Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TreeView item clicked

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.

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

Now I also tried using the MouseLeftButtonDown event of the TreeViewItem like this:

<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?

like image 954
Weixiang Guan Avatar asked May 16 '13 10:05

Weixiang Guan


1 Answers

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.

<TreeView>
  <TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
        <EventSetter Event="MouseDoubleClick"
                Handler="itemDoubleClicked"/>
    </Style>
  </TreeView.ItemContainerStyle>
</TreeView>
like image 68
makc Avatar answered Nov 15 '22 06:11

makc