Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 964
H.B. Avatar asked Jan 20 '11 20:01

H.B.


1 Answers

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>
like image 199
Fredrik Hedblad Avatar answered Nov 13 '22 09:11

Fredrik Hedblad