首页 > 解决方案 > 从上下文菜单中访问列表视图(选定)项目

问题描述

在我的 WPF MVVM(使用 Prism)应用程序中,我有一个列表视图。在此列表视图中,我已将 Ctrl-C 键输入绑定到具有 IList 参数的复制函数。(请参阅 CopyChannelChangeNotificationToClipboardCommand)这很好用。

现在我想添加一个上下文菜单,它有一个具有“复制 Ctrl-C”功能的 MenuItem。我不明白的是如何从 MenuItem 绑定 CommandParameter 以便它提供 ListView 的 Selected 项?这个想法是使用与输入绑定键相同的功能,即从列表视图中获取 IList 以作为命令参数附加。我在这里尝试阅读了很多帖子,尝试了更多,但所有结果都导致 objList 参数为空。如果有人对如何实现这一点有任何建议,我将不胜感激。

我的看法(部分)


<ListView Grid.Row="1" ItemTemplate="{StaticResource ChannelChangeDataTemplateKey}" ItemsSource="{Binding ChannelChangeNotifications}" lb:ListBoxBehavior.ScrollOnNewItem="true">
    <ListView.InputBindings>
        <KeyBinding Key="C" Modifiers="Control" Command="{Binding CopyChannelChangeNotificationToClipboardCommand}" CommandParameter="{Binding Path=SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"/>
    </ListView.InputBindings>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="{x:Static p:Resources.UICopySelectedItems}" Command="{Binding CopySelectedItemsClickCommand}" CommandParameter="{Binding Path=SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"></MenuItem>
        </ContextMenu>
    </ListView.ContextMenu>
</ListView>

和我的视图模型代码


public Prism.Commands.DelegateCommand<IList> CopyChannelChangeNotificationToClipboardCommand => new Prism.Commands.DelegateCommand<IList>(CopyChannelChangeNotificationToClipboard);
public Prism.Commands.DelegateCommand<IList> CopySelectedItemsClickCommand => new Prism.Commands.DelegateCommand<IList>(CopyChannelChangeNotificationToClipboard);

private void CopyChannelChangeNotificationToClipboard(IList objList)
{
  if (objList != null)
  {
    // Copy selected list view objects to clipboard
    // Works well when coming from CopyChannelChangeNotificationToClipboardCommand
    // but not when coming from CopySelectedItemsClickCommand
    // since objList is always null
  }
}

标签: c#wpflistviewmvvmcontextmenu

解决方案


推荐阅读