1

How can I add WPF DelegateCommands to the items in a TreeView bound to an XmlDataProvider? I'm using the MVVM pattern and Composite WPF and I want the command to be called when the user double-clicks on an item in the TreeView.


I have a TreeView defined in XAML whose DataContext is set to the XmlDataProvider:

<TreeView
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ItemsSource="{Binding XPath=/SomeTopElement/*}">
    <TreeView.Resources>
        <HierarchicalDataTemplate
            DataType="SomeElement"
            ItemsSource="{Binding XPath=child::*}">
            <TextBlock Text="{Binding XPath=@SomeAttribute}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

In other parts of the code I simply bind to a DelegateCommand in the ViewModel:

<MenuItem Command="{Binding NewCommand}" Header="_New" />

How can this be done with the above TreeView?

sourcenouveau
  • 29,356
  • 35
  • 146
  • 243

1 Answers1

2

You should use the Attached Command Behavior pattern. This question answers a similar problem, but within a ListView.

Community
  • 1
  • 1
Julien Poulin
  • 12,737
  • 10
  • 51
  • 76
  • I also found another question on StackOverflow (http://stackoverflow.com/questions/926451/how-can-i-attach-two-attached-behaviors-to-one-xaml-element) and an example of general Attached Behaviors with a TreeView (http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx) – sourcenouveau Jul 22 '09 at 13:00
  • @emddudley: yes, your 1st link is the one I used in one of my projects to add a double-clic command to a listbox and it work very well – Julien Poulin Jul 22 '09 at 13:10