【问题标题】:Get name(or index) of selected menu item from context menu, which was dynamically generated via ItemsSource bound to a ObservableCollection从上下文菜单中获取所选菜单项的名称(或索引),该菜单项是通过绑定到 ObservableCollection 的 ItemsSource 动态生成的
【发布时间】:2016-03-25 15:27:54
【问题描述】:

我有一个包含 1 个菜单项的上下文菜单。该菜单项绑定到 itemssource 的 ObservableCollection。

         <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Example Menu Item" 
                          Command="{Binding Path=DataContext.ExampleCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}"
                          ItemsSource="{Binding ObservableItems}">
                </MenuItem>
            </ContextMenu>
        </ListView.ContextMenu>

如何获取所选菜单项的名称(或索引)。问题是我无法将命令绑定到每个单独的菜单项,因为它们是动态生成的。

例如,我如何知道点击了哪个项目,如下图所示?

非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: c# wpf mvvm contextmenu menuitem


    【解决方案1】:

    对于动态生成的列表,您仍然可以为每个项目绑定 CommandCommandParameter,但您需要使用 ItemContainerStyle

    <ContextMenu>
        <MenuItem Header="Example Menu Item" ItemsSource="{Binding ObservableItems}">
            <MenuItem.ItemContainerStyle>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Command" Value="{Binding Path=DataContext.ExampleCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}"/>
                    <Setter Property="CommandParameter" Value="{Binding}"/>
                </Style>
            </MenuItem.ItemContainerStyle>
        </MenuItem>
    </ContextMenu>
    

    在这个例子中CommandParameter,作为参数传递给你ExampleCommand命令,将是你集合中的一个项目(当前DataContext子项目)

    编辑

    要获取索引,您可以使用一对ItemsControl 属性:AlternationCountAlternationIndex。您将 AlternationCount 设置为集合中的项目数,并将 AlternationIndex 传递给您的命令

    <MenuItem Header="Example Menu Item" ItemsSource="{Binding ObservableItems}" AlternationCount="{Binding ObservableItems.Count}">
       <MenuItem.ItemContainerStyle>
          <Style TargetType="{x:Type MenuItem}">
             <Setter Property="Command" Value="{Binding ...}"/>
             <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}, Path=(ItemsControl.AlternationIndex)}"/>
          </Style>
       </MenuItem.ItemContainerStyle>
    </MenuItem>
    

    【讨论】:

    • 能不能得到选中的索引,而不是observablecollection项?
    • 如果你有项目和集合从那里获取索引(它在同一个DataContext
    • 我不太清楚你的意思?您的意思是遍历集合吗?
    • 应该像使用IndexOf(T item)方法一样简单,比如var idx = ObservableItems.IndexOf(selectedItem)
    • 检查我的编辑,你应该得到一个项目的索引而不是项目
    猜你喜欢
    • 2013-03-27
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多