views:

550

answers:

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?

+1  A: 

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

Julien Poulin
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)
emddudley
How to attach commands to any UIElement: http://www.japf.fr/?p=22
emddudley
@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