5

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?

7
  • use SelectedItemChanged event, note that keyboard will get the event called as well Commented May 16, 2013 at 10:22
  • @makc Thanks for the contribution! But I don't want the handler to be called when the selected item changes, but when the user double clicks on the item. Commented May 16, 2013 at 11:26
  • this is not what you have described in the question, did you try MouseDoubleClick event? Commented May 16, 2013 at 11:50
  • @makc Although I did not try MouseDoubleClick, but I read the document about it, and it will be called whenever wherever the user double clicks on the control (tree view), and again the sender is then the tree view, but not the TreeViewItem. Commented May 16, 2013 at 13:39
  • yes you are right, but you forget the fact that the item you clicked/double clicked has become selected item and you can easily access it unless you changed the selector functionality in that case post your code Commented May 16, 2013 at 13:43

1 Answer 1

7

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.