Subscribe to events launched by children of an ItemsControl

 
 
  • GĂ©rald BarrĂ©
 

The ItemsControls (Listbox, Treeview, Menu, 
) are often used. Sometimes you want to subscribe to the events of all their children. However this can be hard to set up especially when using binding. Fortunately there is a very easy solution (you could suspect it 😃). Simply change the style of the container (ItemsControl) and use the EventSetter tag:

XAML
<TreeView>
  <TreeView.Style>
    <Style>
      <EventSetter Event="TreeViewItem.Selected"
                   Handler="event_handler" />
    </Style>
  </TreeView.Style>
  <TreeViewItem Header="Item niveau 1 : 1" />
  <TreeViewItem Header="Item niveau 1 : 2"/>
  <TreeViewItem Header="Item niveau 1 : 3"/>
  <TreeViewItem Header="Item niveau 1 : 4">
    <TreeViewItem Header="Item niveau 2 : 1"/>
    <TreeViewItem Header="Item niveau 2 : 2"/>
    <TreeViewItem Header="Item niveau 2 : 3"/>
  </TreeViewItem>
  <TreeViewItem Header="Item niveau 1 : 5"/>
</TreeView>

With this method the sender of the event is the TreeView which can be annoying according to what one wants to do. It may be more appropriate for the sender to be the TreeViewItem. To do this, you must apply the style on the TreeViewItem instead of the TreeView. To do this, you must create a Style in the Treeview and set the TargetType to TreeViewItem:

XAML
<TreeView>
  <TreeView.Resources>
    <Style TargetType="{x:Type TreeViewItem}">
      <EventSetter Event="Selected"
                   Handler="event_handler" />
    </Style>
  </TreeView.Resources>
  <TreeViewItem Header="Item niveau 1 : 1 "/>
  <TreeViewItem Header="Item niveau 1 : 2 "/>
  <TreeViewItem Header="Item niveau 1 : 3 "/>
  <TreeViewItem Header="Item niveau 1 : 4 ">
    <TreeViewItem Header="Item niveau 2 : 1 "/>
    <TreeViewItem Header="Item niveau 2 : 2 "/>
    <TreeViewItem Header="Item niveau 2 : 3 "/>
  </TreeViewItem>
  <TreeViewItem Header="Item niveau 1 : 5"/>
</TreeView>

Do you have a question or a suggestion about this post? Contact me!

Follow me: