如何从树视图中的contextmenu绑定到基本视图模型?

时间:2018-01-23 19:10:35

标签: c# wpf mvvm treeview

我无法在contextMenu中选择绑定到我的命令EditCommand。我的树视图中的按钮很好地绑定它,但在菜单中它失败了。我已经读过这很可能是因为contextMenu位于不同的UI树中,但使用findAncestor和标签的解决方案对我来说并不起作用。反正是否仍然可以将treeViewItem传递给方法?

我的XAML:

<TreeView Background="Transparent"
          Margin="10"
          Grid.Column="0" Grid.Row="1"
          ItemsSource="{Binding Path=TreeViewItems}">
    <TreeView.ItemTemplate >
        <HierarchicalDataTemplate DataType="{x:Type model:TreeViewSelection}" ItemsSource="{Binding Configs}" >
            <DockPanel HorizontalAlignment="Stretch" Background="Transparent"><!--Transparency allows context click on whole row-->
                <DockPanel.ContextMenu>
                    <ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
                        <MenuItem 
                            Header="Edit"
                            Command="{Binding ElementName=userControl, Path=DataContext.EditCommand}"<!--Doesn't work-->
                            CommandParameter="{Binding}">
                            <MenuItem.Icon>
                                <Image Source="../Images/edit.png" />
                            </MenuItem.Icon>
                        </MenuItem>
                    </ContextMenu>
                </DockPanel.ContextMenu>
                <TextBlock DockPanel.Dock="Left" Text="{Binding Title}" />
                <StackPanel DockPanel.Dock="Right"
                            Orientation="Horizontal"
                            HorizontalAlignment="Right">
                    <Button Height="23" Width="23"
                        Command="{Binding ElementName=userControl, Path=DataContext.EditCommand}"<!--Works-->
                        CommandParameter="{Binding}"
                        Style="{DynamicResource ImageNoTextButton}"
                        inf:AttachedProperties.Image="../Images/edit.png"
                        inf:AttachedProperties.ImageMouseOver="../Images/editMouseOver.png" />
                </StackPanel>
            </DockPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>

</TreeView>

1 个答案:

答案 0 :(得分:0)

试试这个:

<DockPanel HorizontalAlignment="Stretch" Background="Transparent"
           Tag="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}">
    <DockPanel.ContextMenu>
        <ContextMenu>
            <MenuItem 
                Header="Edit"
                Command="{Binding Path=PlacementTarget.Tag.DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                CommandParameter="{Binding}">
                <MenuItem.Icon>
                    <Image Source="../Images/edit.png" />
                </MenuItem.Icon>
            </MenuItem>
        </ContextMenu>
    </DockPanel.ContextMenu>
    ...
</DockPanel>