【问题标题】:How to set ContextMenu of a bound item?如何设置绑定项目的 ContextMenu?
【发布时间】:2009-09-09 04:18:21
【问题描述】:

我正在努力实现以下目标:

<Style TargetType="ListBoxItem">
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <MenuItem Name="mnuEdit" Header="_Edit" Click="MenuItem_Click" />
            </ContextMenu>
        </Setter.Value>
    </Setter>
<Style>

但它会抛出以下异常:

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

【问题讨论】:

    标签: wpf styles contextmenu listboxitem setter


    【解决方案1】:

    试试这个:

    <ContextMenu x:Key="contextMenu">
        <MenuItem Name="mnuEdit" Header="_Edit" Click="MenuItem_Click" />
    </ContextMenu>
    
    <Style TargetType="ListBoxItem">
        <Setter Property="ContextMenu" Value="{DynamicResource contextMenu}" />
    </Style>
    

    【讨论】:

    • 好的,但是为什么呢?其他属性无需使用静态或动态资源即可设置。
    • @jrwren,好点子。我的 猜测 是,如果您按照问题中显示的方式进行操作,则会为每个菜单项创建一个上下文菜单,当您只需要一个时,这可能会造成浪费。我知道这不是一个决定性的解释。
    • 我想要一个具体的答案。知道为什么肯定会帮助我理解 WPF。
    猜你喜欢
    • 2011-02-20
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多