我的WPF应用程序中有listview控件的工作上下文菜单。我想要启用上下文菜单项,如果用户右键单击列表视图项但禁用它们是在listview的面板区域上单击。 谢谢 MK
更新:这是我的列表视图,但我想在用户点击面板区域时禁用MenuItems“Remove”和“Calculate”。感谢您的回复
<ListView Name="lb_proplist" DisplayMemberPath ="Name" HorizontalAlignment="Left" ToolTip="Use right click to see more options"
ItemsSource="{Binding Converter={StaticResource FilterByPropTypeConverter}}" Margin="0,0,0,0"
ContextMenuOpening="ContextMenu_ContextMenuOpening" >
<ListView.ContextMenu>
<ContextMenu >
<MenuItem Name="cmi_addNew" Header="Add New"
Command="{Binding AddNewItemItem}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<MenuItem Name="cmi_remove" Header="Remove"
Command="{Binding RemoveItem}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
Path=PlacementTarget.SelectedItem}" />
<MenuItem Name="cmi_calculate" Header="Calculate"
Command="{Binding CalculateItem}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
Path=PlacementTarget.SelectedItem}" />
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="200"/>
</GridView>
</ListView.View>
</ListView>
答案 0 :(得分:2)
嗯,这可以使用ListView的 ItemsTemplate 属性来完成:
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel Tag = "{Binding DataContext, ElementName=myListView}">
<TextBlock Text="{Binding}"/>
<DockPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Local Item 1"
Command="{Binding Path=PlacementTarget.Tag.CommandName, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
<MenuItem Header="Local Item 2"/>
</ContextMenu>
</DockPanel.ContextMenu>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
例如, ContextMenu 仅针对项目创建,但不针对整个控件创建。
此外,标记会添加到 DockPanel 中以访问原始DataContext。
好吧,如果是 GridView ,您需要覆盖 ListViewItem 的样式,并将 ContextMenu 绑定为 StaticResource
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="Add New"/>
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}"/>
</Style>
</ListView.ItemContainerStyle>