Setting event handlers inside a Setter.Value structure
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 1开发者_如何学Python02 '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>
You can just ListBoxItem.HorizontalContentAlignment
to Stretch
and then put the ContextMenu
in your ListBox.ItemTemplate
. Here's an example:
<Grid>
<Grid.Resources>
<PointCollection x:Key="sampleData">
<Point X="10" Y="20"/>
<Point X="30" Y="40"/>
</PointCollection>
</Grid.Resources>
<ListBox Width="100" ItemsSource="{StaticResource sampleData}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="Red">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Test" Click="MenuItem_Click"/>
</ContextMenu>
</Grid.ContextMenu>
<TextBlock Text="{Binding}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
精彩评论