Search code examples
wpftreeviewcommandselecteditemchanged

How to bind a Command to SelectedItemChanged event of a TreeView


There is a Treeview Control.

 <TreeView Name="ProductsHierarchy" FontFamily="Arial"  
                          Background="White" Margin="2" 
                          FontSize="12" SelectedItemChanged ="ProductsHierarchy_SelectedItemChanged">

Is there a way to bind a command for SelectedItemChanged event of the treeview, avoiding the code behind event handler?


Solution

  • Try MVVM Toolkit's EventToCommand.

    "Built-in" (from Blend) approach is to use Interactivity

    <TreeView Name="ProductsHierarchy" FontFamily="Arial"  
                              Background="White" Margin="2" 
                              FontSize="12" SelectedItemChanged ="ProductsHierarchy_SelectedItemChanged">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectedItemChanged">
                <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" CommandParameter="argument"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TreeView>
    

    You must include namespace:

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    The disadvantage here is that you have no access to EventArgs. Here's the solution (it's in Polish, but code samples are pretty much self-explanatory).