在Setter.Value结构中设置事件处理程序 [英] Setting event handlers inside a Setter.Value structure

查看:448
本文介绍了在Setter.Value结构中设置事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListView ,我想设置一个上下文菜单,我可以打开不仅在右侧点击某些列中的某些文本,而且 ListViewItem ,为了做到这一点,我以为我只是使用样式设置器设置我的 ContextMenu ,因为我无法直接访问 ListViewItem

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>




错误102'处理程序'无效。
'点击'不是
'System.Windows.Controls.GridView'上的事件。

Error 102 'Handler' is not valid. 'Click' is not an event on 'System.Windows.Controls.GridView'.

我认为您可以通过使用 EventSetter 单击 -event来避免此问题。但是很明显,代码从你需要的所有包装标签中获得相当的膨胀。

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.

我的问题是如果有一些解决方法,所以你不必处理 EventSetters

My question is if there is some workaround so you do not have to deal with EventSetters.

编辑: 此问题,以了解为何发生此错误的解释。

See this question for an explanation on why this error occurs.

推荐答案

您可以将 ContextMenu 放在 ListView 的资源,然后将其用作静态资源,这样您就不必为 MenuItem

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>

这篇关于在Setter.Value结构中设置事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆