WPF声明样式的ContextMenu

时间:2019-02-22 13:27:51

标签: c# wpf contextmenu

我为带有ListViewItem的{​​{1}}创建了样式,以便当我右键单击ContextMenu时可以通过ListViewItem删除/删除它。

ContextMenu

还有我的<Style x:Key="GridViewCheckoutColumnStyle" TargetType="{x:Type ListViewItem}"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem Header="Remove" Click="ListViewItem_ContextMenuClick"/> </ContextMenu> </Setter.Value> </Setter> </Style>

ListView

可悲的是,每当我尝试运行该代码时,该代码都会引发错误。我收到无效的强制转换异常,说它无法将<ListView Name="ListViewCheckoutTable" Margin="20,20,20,0" VerticalAlignment="Top" Height="200" FontSize="14" ItemContainerStyle="{StaticResource GridViewCheckoutColumnStyle}"> <ListView.View> <GridView> <GridViewColumn Header="Quantity" Width="80" DisplayMemberBinding="{Binding Quantity}"/> <GridViewColumn Header="Name" Width="150" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Price" Width="70" DisplayMemberBinding="{Binding Price}"/> </GridView> </ListView.View> </ListView> 转换为MenuItem

我还要说的是,我的Grid充满了ListView

MenuItems

1 个答案:

答案 0 :(得分:2)

尝试将ContextMenu定义为单独的资源:

<ContextMenu x:Key="contextMenu" x:Shared="False">
    <MenuItem Header="Remove" Click="ListViewItem_ContextMenuClick"/>
</ContextMenu>
<Style x:Key="GridViewCheckoutColumnStyle" TargetType="{x:Type ListViewItem}">
    <Setter Property="ContextMenu" Value="{StaticResource contextMenu}" />
</Style>