我正在使用 HierarchicalDataTemplates 构建 TreeView ,并希望将节点绑定(bind)到 MainViewModel 中的命令。我猜想与范围存在一些冲突,因为如果我例如,绑定(bind)就可以工作。使用按钮并在 TreeView 之外定义它。但是,如果我在内部定义它,它就不起作用。
我在 Stackoverflow 上进行了搜索,找到了几种解决方案,但没有一个对我有用。杰霍夫例如建议here使用
<Button Command="{Binding DataContext.Command,
RelativeSource={RelativeSource AncestorLevel=2, AncestorType=TreeViewItem}}"
CommandParameter="{Binding}" />
但这没有用。感谢您的任何建议!
<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>
最佳答案
您的 TreeView
-Control 是否位于 Window
或 UserControl
内?
如果您位于窗口
内:
<Button Command="{Binding DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" CommandParameter="{Binding}" />
以及UserControl
<Button Command="{Binding DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding}" />
关于c# - 从 TreeView 中绑定(bind)到命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207660/