【问题标题】:Dynamically have a ContextMenu for every ListViewItem in a ListView?为 ListView 中的每个 ListViewItem 动态地拥有一个 ContextMenu?
【发布时间】:2012-02-29 23:16:52
【问题描述】:

我目前在 ListView 上有一个 ContextMenu,其视图样式设置为“GridView”。但是,这给我带来了麻烦,因为您可以右键单击 ListView 顶部的可视列以显示上下文菜单。

我只希望上下文菜单出现在列表中的所有项目上,我不想编写一个方法来为每个列表添加一个新的上下文菜单。

有没有一种聪明的方法来做到这一点?也许通过某种模板?哪种方法最好?

【问题讨论】:

    标签: wpf


    【解决方案1】:

    您可以创建一种样式,该样式将应用于列表视图中的项目,而不是列表视图本身。比如:

    <ListView>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Header="Send Email" />
                            <MenuItem Header="Delete" />
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>
    

    【讨论】:

      【解决方案2】:

      作为参考,我无法让它像这样工作,因为它一直导致错误:

      A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
      
      Additional information: 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 '<file>'.
      

      相反,我不得不使用静态资源,虽然结果完全相同,但实际上确实有效。去图吧。

      <ListView.ItemContainerStyle>
          <Style TargetType="ListViewItem">
              <Setter Property="ContextMenu" Value="{StaticResource ListViewContextMenu}" />
          </Style>
      </ListView.ItemContainerStyle>
      
      <Application.Resources>
          <ContextMenu x:Key="ListViewContextMenu">
              <MenuItem Header="Play" />
          </ContextMenu>
      </Application.Resources>
      

      【讨论】:

        猜你喜欢
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-12
        • 2011-11-30
        • 1970-01-01
        • 2022-06-17
        • 2013-09-26
        相关资源
        最近更新 更多