简体   繁体   中英

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 eg 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 eg 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>

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}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM