Search code examples
wpfxamlmvvmcommandtreeviewitem

Make TreeViewItem control execute command when double clicked


I'm looking for a way, in WPF, to bind commands to a TreeViewItem, so when I double click a TreeViewItem a ICommand is executed in my ViewModel (MVVM pattern). Much like the Visual Studio Solution Explorer.

I was hoping that I could use something like AttachedCommandBehaviour but that does not work. I guess it's because that the TreeViewItem itself does not support Commands.

Here is my test implementation which doesn't work:

<TreeViewItem Header="Opret produktions ordre">
    <acb:CommandBehaviorCollection.Behaviors>
        <acb:BehaviorBinding Event="MouseLeftButtonDown" Command="{Binding TestCommand}"/>
    </acb:CommandBehaviorCollection.Behaviors>
</TreeViewItem>

Does anyone have a suggestion on how to make this work? Or maybe you know of a control that give me this functionality? I am of course hoping for a MVVM friendly solution. Preferably all in XAML.


Solution

  • Have you tried InvokeDataCommand trigger from the CodePlex Expression Blend sample library?

    <i:EventTrigger EventName="Click">
          <si:InvokeDataCommand Command="{Binding ShoppingCart.CheckOutCommand}"/>
    </i:EventTrigger>
    

    You will need the fixed version though if you're using WPF4, read about the issue here: http://blog.thekieners.com/2010/11/09/expression-blend-samples-not-working-with-silverlight-4-and-wpf-4/

    Download the sample solution from here (this is the updated version): http://expressionblend.codeplex.com/workitem/8148