0

GOAL: I am trying to expand my treeview items using a single click. I need to access the DataContext of selected node and set the property for expanding/collapsing.

What I have tried I have put EventSetter on TreeViewItem for MouseLeftButtonUp (MLBU) & PreviewMouseLeftButtonUp. However, when a click on a leaf node, in the MLBU handler I get the Header property of sender as Parent and not leaf. The OriginalSource is correctly pointing to leaf control. But if I use that I will have to determine all the type of Sources and then get the value out of it.

Is there any other way to accomplish this?

EDIT

XAML for setting the event:

<Style TargetType="TreeViewItem" BasedOn="{StaticResource SomeStyle}">
<Setter Property="IsExpanded" Value="{Binding Path=IsExpanded, Mode=TwoWay}"/>
<EventSetter Event="PreviewMouseLeftButtonUp" Handler="OnPreviewMouseLeftButtonUp"/>
<EventSetter Event="MouseLeftButtonUp" Handler="OnMouseLeftButtonUp"/>
</Style>

The treeview items have different datatemplate based on requirement. So in OriginalSource it can be either Image or System.Windows.Documents.Run (coming for Label). Thus, I have to put if-else for each type of control I create. Whereas, my DataContext has top level interface for each item whose property I can set to expand it. So a generic conversion will work.

Piyush Parashar
  • 866
  • 8
  • 20
  • If your handlers are for just `TreeViewItem`, the `OriginalSource` should be `TreeViewItem`, and in XAML you should specify the owner for event such as `TreeViewItem.MouseLeftButtonUp` instead of just `MouseLeftButtonUp`. It's a bit hard to get what you mean by this *I will have to determine all the type of Sources* - this can happen if you have one handler for many types of event (and depending on how you set the `Handler` property of EventSetter). – Hopeless Oct 09 '15 at 07:30
  • Thanks for replying @Hopeless. I have updated XAML and other details. Please see. I do not have a generic handler for all types. It is only for `TreeViewItem` – Piyush Parashar Oct 09 '15 at 08:23
  • I've just played around with TreeView. Looks like you can check out the `Source` instead. It should always be the directly interacted `TreeViewItem`. The `sender` is always the top-level TreeViewItem. – Hopeless Oct 09 '15 at 09:12
  • Doesn't this answer suit you? http://stackoverflow.com/questions/2921972/how-to-expand-wpf-treeview-on-single-click-of-item – netaholic Oct 09 '15 at 09:28
  • @netaholic thanks for replying. I saw this and it looks like this might work. However for one particular treeviewitem for which I am creating a `Label` with `AccessText` property, the OriginalSource is `System.Windows.Documents.Run`. This type is not `Visual` or `Visual3d` because of which `VisualTreeHelper.GetParent` throws exception. Do you have any idea about this? – Piyush Parashar Oct 09 '15 at 11:56

0 Answers0