WPF上下文菜单,其菜单项定义为数据模板 [英] WPF context menu whose items are defined as data templates

查看:86
本文介绍了WPF上下文菜单,其菜单项定义为数据模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示项目集合的列表视图,每个项目都有一个视图模型(MVVM)作为其基础数据.

I have a list view that displays a collection of items, each item has as its underlying data a view model (MVVM).

我想做的是当用户右键单击这些列表视图项之一时,在上下文菜单中显示不同的菜单项.显示的菜单项取决于所选项目的类型(即基础视图模型的类型).

What I would like to do is display different menu items within the context menu when the user right clicks one of these list view items. The menu items displayed is dependent on the type of the item selected (i.e. the type of the underlying view model).

我希望以下内容可以正常工作,但不能(在上下文菜单中不显示任何项目).

I would expect the below to work, but it does not (no items are displayed in the context menu).

<ListView.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}}">
    <ContextMenu.Resources>                        
        <DataTemplate DataType="{x:Type ViewModels:ViewModel1}">
            <MenuItem Header="DoStuffForVM1" Command="{Binding DoStuffForVM1Command}"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ViewModels:ViewModel2}">
            <MenuItem Header="DoStuffForVM2" Command="{Binding DoStuffForVM2Command}"/>
        </DataTemplate>
    </ContextMenu.Resources>
    <ContentPresenter ContentSource="{Binding}" />
</ContextMenu>
</ListView.ContextMenu>

有什么想法吗?

谢谢.

推荐答案

这对我有用:

<ListView.ContextMenu>
<ContextMenu>
 <ContentPresenter Content="{Binding Path=PlacementTarget.SelectedItem, 
                             RelativeSource={RelativeSource AncestorType=ContextMenu}}" >
    <ContentPresenter.Resources>                        
        <DataTemplate DataType="{x:Type ViewModels:ViewModel1}">
            <MenuItem Header="DoStuffForVM1" Command="{Binding DoStuffForVM1Command}"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ViewModels:ViewModel2}">
            <MenuItem Header="DoStuffForVM2" Command="{Binding DoStuffForVM2Command}"/>
        </DataTemplate>
    </ContentPresenter.Resources>
  </ContentPresenter>
</ContextMenu>
</ListView.ContextMenu>

这篇关于WPF上下文菜单,其菜单项定义为数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆