【问题标题】:Bind to command from within a treeview从树视图中绑定到命令
【发布时间】:2015-03-23 10:14:42
【问题描述】:

我正在使用 HierarchicalDataTemplates 构建树视图,并希望将节点绑定到 MainViewModel 中的命令。我想与范围存在一些冲突,因为如果我例如绑定有效使用一个按钮并在树视图之外定义它。但是,如果我在里面定义它,它就不起作用。

我搜索了 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>

【问题讨论】:

    标签: c# wpf treeview


    【解决方案1】:

    您的TreeView-Control 是否在WindowUserControl 内?

    如果你在Window

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

    【讨论】:

    • 非常感谢!它在窗户里 - 就像一个魅力!
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多