【问题标题】:Set CommandParameter to a different Binding than the Commands "RelativeSource Binding"将 CommandParameter 设置为与命令“RelativeSource Binding”不同的绑定
【发布时间】:2020-04-02 15:50:54
【问题描述】:

我想将 CommandParameter 绑定到另一个 ViewModel,然后是 Command。 命令绑定从树视图的集合中跳出到包含“项目”的 ViewModel - 集合。但是 CommandParameter 应该从“Children”传递 ViewModel。 如果我只是做 {Binding} 它会传递错误的 ViewModel。 (“Items”集合所在的那个)

<TreeView 
                ItemsSource="{Binding Items}">
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                        <StackPanel Orientation="Horizontal" 
                                    CanHorizontallyScroll="True">
                            <CheckBox VerticalAlignment="Center" 
                                      IsChecked="{Binding IsSelected}"/>
                            <TextBlock VerticalAlignment="Center" 
                                       FontSize="14"
                                       Text="{Binding Name}"/>
                        </StackPanel>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
                <TreeView.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Set Script-Root"
                                  Command="{Binding Path=DataContext.SomeCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                                  CommandParameter="{Binding HOW_TO_VIEWMODEL_of_TREEVIEW-ITEMS???}"/>
                    </ContextMenu>
                </TreeView.ContextMenu>
            </TreeView>

【问题讨论】:

    标签: c# wpf xaml mvvm binding


    【解决方案1】:

    要完成这项工作,您需要将ContextMenu 设置为TreeViewItem。

    这将使您能够设置:

    CommandParameter="{Binding}"
    

    这将是TreeViewItem 的DataContext,并且:

    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, Path=DataContext.SomeCommand}"
    

    这将获得TreeView 中的DataContext。

    我希望这会有所帮助。

    【讨论】:

    • 能否请您告诉或显示我必须在哪里定义 ContextMenu。它不起作用。是 吗?
    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2011-06-28
    • 1970-01-01
    相关资源
    最近更新 更多