简体   繁体   English

从树视图绑定到命令

[英]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. 我正在使用HierarchicalDataTemplates构建树视图,并希望将节点绑定到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. 我搜索了Stackoverflow,发现了几种解决方案,但没有一种对我有用。 Jehof eg suggested here to use Jehof例如在这里建议使用

<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 ? 您的TreeView -Control是在Window还是UserControl

If you are inside a Window : 如果您在Window

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

and for UserControl UserControl

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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