WPF MVVM将命令绑定到treeview上下文菜单

时间:2017-08-19 06:50:21

标签: c# wpf xaml mvvm treeview

我有一个树视图,我希望右键单击一个菜单。在单击菜单项时,应该使用该项调用命令。我尝试过不同的解决方案,但不断收到如下错误。

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression

我的树视图如下

   <TreeView ItemsSource="{Binding Buildings}" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" Grid.RowSpan="4">
                    <TreeView.Resources>
                        <HierarchicalDataTemplate  ItemsSource="{Binding Gates}" DataType="{x:Type local:Floor}">

                            <TextBlock Text="{Binding Name}" />
                        </HierarchicalDataTemplate>
                        <HierarchicalDataTemplate ItemsSource="{Binding Floors}" DataType="{x:Type local:Building}">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Name}" >
                                    <TextBlock.ContextMenu>
                                        <ContextMenu>
                                            <ContextMenu.ItemContainerStyle>
                                                <Style TargetType="MenuItem">
                                                    <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.EditCmd}"/>
                                                </Style>
                                            </ContextMenu.ItemContainerStyle>
                                        </ContextMenu>
                                    </TextBlock.ContextMenu>
                                </TextBlock>
                            </StackPanel>
                        </HierarchicalDataTemplate>
                        <DataTemplate DataType="{x:Type local:Gate}">
                            <TextBlock Text="{Binding Name}" />
                        </DataTemplate>
                    </TreeView.Resources>
                </TreeView>

同样在viewmodel中

   private ICommand editCmd;
    public ICommand EditCmd
    {
        get
        {
            if (editCmd == null)
                editCmd = new DelegateCommand(EditObjectFunction);
            return editCmd;
        }
    }

我尝试了不同的解决方案,例如This,但无法解决问题

1 个答案:

答案 0 :(得分:0)

UserControl不是MenuItem的视觉祖先,因为ContextMenu位于其自己的元素树中。

但是您可以将Tag的{​​{1}}属性绑定到TextBlock,然后将UserControl的{​​{1}}属性绑定到Command MenuItem的属性:

PlacementTarget