[英]How to copy selected listview item by copy command in the context menu
我有一個列表視圖,我想通過在上下文菜單中選擇復制命令來復制所選項目。 我可以使用copy命令創建上下文菜單,如下圖所示:
問題是當我選擇一個行項目並右鍵單擊它時,上下文菜單不會顯示,並且我無法選擇復制命令來復制所選項目。 當我右鍵單擊列表視圖中的空白區域時,將顯示上下文菜單。
這是代碼:
的.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;
}
}
這樣的事情將使您可以將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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.