简体   繁体   中英

WPF Declare ContextMenu in Style

I created a style for a ListViewItem with a ContextMenu so that when I right click on a ListViewItem I can delete/remove it via the 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>

And my 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>

Sadly this code throws an error whenever I try to run it. I get an invalid cast Exception saying that it cannot convert MenuItem into Grid .

What I should also say is that my ListView is filled with MenuItems

public class MenuItem 
{
    public int Quantity { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
}

Try to define the ContextMenu as a separate resource:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM