Dynamically have ContextMenu for each ListViewItem in a ListView?

I currently have a ContextMenu in a ListView with its view style set to "GridView". However, this is causing me problems because you can right-click the visual columns at the top of the ListView to also display the context menu.

I want the context menu to be displayed in all elements of the list, and it would be very difficult for me to program a method to add a new context menu for each list.

Is there any reasonable way to do this? Maybe through some kind of template? Which approach would be best?

+3
source share
2 answers

, , . - :

<ListView>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="Send Email" />
                        <MenuItem Header="Delete" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>
+8

, :

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: Cannot add content of type 'System.Windows.Controls.ContextMenu' to an object of type 'System.Object'.  Error at object 'System.Windows.Controls.ContextMenu' in markup file '<file>'.

, , , . .

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="ContextMenu" Value="{StaticResource ListViewContextMenu}" />
    </Style>
</ListView.ItemContainerStyle>

<Application.Resources>
    <ContextMenu x:Key="ListViewContextMenu">
        <MenuItem Header="Play" />
    </ContextMenu>
</Application.Resources>
+3

Source: https://habr.com/ru/post/1785073/


All Articles