How to bind a Command to SelectedItemChanged event of a TreeView

user1874589 picture user1874589 · Dec 12, 2012 · Viewed 7.7k times · Source

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?

Answer

amnezjak picture amnezjak · Dec 12, 2012

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).