I have a ListView
and i'd like to set up a context menu which i can open not only when right-clicking some text in some column but anywhere on the ListViewItem
, to do so i thought i'd just set my ContextMenu
using a style setter since i cannot directly access the ListViewItem
.
Unfortunately when you try to do it like this it won't compile:
<Style TargetType="ListViewItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Header" Click="Handler"/>
...
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
Error 102 'Handler' is not valid. 'Click' is not an event on 'System.Windows.Controls.GridView'.
I figured that you can avoid this by using an EventSetter
for the Click
-event. But it is apparent that the code gets quite inflated from all the wrapping tags you need.
My question is if there is some workaround so you do not have to deal with EventSetters
.
Edit: See this question for an explanation on why this error occurs.
You can put the ContextMenu
in the ListView
's Resources and then use it as a static resource, that way you won't have to use a Style for the MenuItem
's
<ListView ...>
<ListView.Resources>
<ContextMenu x:Key="listViewContextMenu">
<MenuItem Header="Header" Click="MenuItem_Click"/>
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="ContextMenu" Value="{StaticResource listViewContextMenu}"/>
</Style>
</ListView.ItemContainerStyle>
<!--...-->
</ListView>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With