peter
peter

Reputation: 2103

Bind to command from within a treeview

I'm building a treeview with HierarchicalDataTemplates and would like to bind the nodes to a command from my MainViewModel. I guess there is some conflict with the scopes, since the binding works if I e.g. use a button and define it outside of the treeview. If I define it inside, however, it does not work.

I've searched through Stackoverflow and found several solutions but none that worked for me. Jehof e.g. suggested here to use

<Button Command="{Binding DataContext.Command, 
    RelativeSource={RelativeSource AncestorLevel=2, AncestorType=TreeViewItem}}"
    CommandParameter="{Binding}" />

but that did not work. Thank you for any suggestions!

<TreeView ItemsSource="{Binding _questions}" Grid.Row="0" Margin="10" BorderThickness="1">
<TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:Question}" ItemsSource="{Binding Converter={StaticResource QuestionConverter}}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="{x:Type local:MainOption}" ItemsSource="{Binding MainOptions}">
        <StackPanel Orientation="Horizontal">
    <CheckBox Content="{Binding Path=Name}" />

/////////////////////////////////////
    <Button Command="{Binding ThisIsMyCommand}" Content="Click Me"/>
/////////////////////////////////////

</StackPanel>
    </HierarchicalDataTemplate>
</TreeView.Resources>

Upvotes: 2

Views: 933

Answers (1)

Tomtom
Tomtom

Reputation: 9384

Is your TreeView-Control inside a Window or UserControl?

If you are inside a Window:

<Button Command="{Binding DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" CommandParameter="{Binding}" />

and for UserControl

<Button Command="{Binding DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding}" />

Upvotes: 3

Related Questions