如何通过上下文菜单中的复制命令复制选定的列表视图项

时间:2015-08-20 06:39:09

标签: c# wpf xaml listview copy

我有一个列表视图,我想通过在上下文菜单中选择复制命令来复制所选项目。我可以使用复制命令创建上下文菜单,如下图所示:

enter image description here

问题是,当我选择一个行项并右键单击它时,上下文菜单将无法显示,我无法选择复制命令来复制所选项。当我右键单击列表视图中的空白区域时,将显示上下文菜单。

enter image description here

以下是代码:

的.xaml

<ListView x: Name = "DebugLogLb" BorderBrush = "{x:Null}" SelectionMode = "Extended" MouseRightButtonDown = "DebugLogLb_MouseRightButtonDown">
  <ListViewItem x: Name = "DebugLogItem">
    <ListViewItem.ContextMenu>
      <ContextMenu x: Name = "CommandMenu">
        <MenuItem Header = "Clear log" Click = "CommandMenuItem_Click"/>
        <MenuItem Header = "Copy" Command = "Copy" CommandTarget = "{Binding ElementName=DebugLogItem}"/>       
      </ContextMenu>
    </ListViewItem.ContextMenu>
  </ListViewItem>
</ListView >

.xaml.cs:

 private void DebugLogLb_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
 {
   ContextMenu contextMenu = this.FindName("CommandMenu") as ContextMenu;
   contextMenu.PlacementTarget = sender as ListViewItem;
   contextMenu.IsOpen = true;
 }

 private void CommandMenuItem_Click(object sender, RoutedEventArgs e) 
 {
   MenuItem menuItem = (MenuItem) e.OriginalSource;

   switch (menuItem.Header.ToString())
   {
     case "Clear log":
       DebugLogLb.Items.Clear();
       break;
     default:
       break;
   }
 }

1 个答案:

答案 0 :(得分:0)

这样的东西可以让你使用ContextMenu及其MenuItems:

       <ListView x:Name = "DebugLogLb" BorderBrush = "{x:Null}" SelectionMode = "Extended" ItemsSource="{Binding items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}">
                    <TextBlock.ContextMenu >
                        <ContextMenu x:Name = "CommandMenu">
                            <MenuItem Header = "Clear log" />
                            <MenuItem Header = "Copy" Command = "Copy" CommandTarget = "{Binding ElementName=DebugLogItem}"/>
                        </ContextMenu>
                    </TextBlock.ContextMenu>
                </TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView >

因此,在ItemTemplate中定义它,以便在选择每个项目时能够使用它。

items集合在后面的代码中定义:

    public ObservableCollection<string> items { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        items = new ObservableCollection<string>();
        items.Add("first item");
        items.Add("second item");
    }

没什么特别的,只是为了举例。

还有一件事,如果您在单击空白区域时仍希望它可用,请在ListView上添加ContextMenu:

          <ListView.ContextMenu>
            <ContextMenu x:Name = "CommandMenu">
                <MenuItem Header = "Clear log" />
                <MenuItem Header = "Copy" Command = "Copy" CommandTarget = "{Binding ElementName=DebugLogItem}"/>
            </ContextMenu>
        </ListView.ContextMenu>