c# - 从 TreeView 中绑定(bind)到命令

标签 c# wpf treeview

我正在使用 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 是否位于 WindowUserControl 内?

如果您位于窗口内:

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

相关文章:

c# - 多线程、lambdas 和局部变量

wpf - 在 App.xaml 中定义颜色并用作静态资源

c# - 在 WPF 中,MVVM 应该 ViewModel 参与打开一个窗口,例如关于窗口?

C# 将多个文本框绑定(bind)到数据库

c# - 我们可以用 C# 编写自己的语言结构吗?

c# - SqlConnection On Before Close 事件?

wpf - 在 WPF 中制作可移动控件

c# - WPF - DataGrid 不应处理 Ctrl+A

c# - 在 TreeView 控件中隐藏节点

.net - 我可以将节点文本包装在WinForms TreeView中吗