我希望在单击ListView中的项目时有一个上下文菜单
<ListView x:Name="resultsView" Grid.Column="1" Margin="10" Grid.Row="1" FontFamily="Verdana" FontSize="14">
<ListView.ContextMenu>
<ContextMenu FontFamily="Verdana" FontSize="14">
<MenuItem Header="Open Folder" Click="openFolder_Click" FontFamily="Verdana" FontSize="14"/>
<Separator/>
<MenuItem Header="Copy Path" Click="copyPath_Click" FontFamily="Verdana" FontSize="14"/>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView x:Name="gridView">
<GridViewColumn x:Name="name" Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn x:Name="folder" Header="Folder" DisplayMemberBinding="{Binding Folder}"/>
<GridViewColumn x:Name="location" Header="Path" DisplayMemberBinding="{Binding Location}"/>
</GridView>
</ListView.View>
</ListView>
以下是我如何向ListView添加项目(结果是SearchFolder的列表):
results.Add(new SearchFolder { Name = Path.GetFileName(directory), Folder = Path.GetFileName(Path.GetDirectoryName(directory)), Location = directory });
resultsView.ItemsSource = results;
我的SearchFolder类
class SearchFolder
{
public string Name { get; set; }
public string Folder { get; set; }
public string Location { get; set; }
}
如何创建ContextMenu,其中对ListView中单击的项执行操作(复制路径或打开文件夹)?
/ edit:这样,无论我在哪里右击,ContextMenu都会显示出来。但我找不到一种方法来访问点击的项目,这不起作用:
MenuItem temp = sender as MenuItem;
if (temp != null)
{
ContextMenu anotherTemp = temp.Parent as ContextMenu;
if (anotherTemp != null)
{
ListViewItem clickedItem = anotherTemp.PlacementTarget as ListViewItem;
if (clickedItem != null)
{
Console.WriteLine("Copy Path " + clickedItem.Name);
}
}
}
答案 0 :(得分:3)
ListView有一个事件“SelectionChanged”。使用此事件,您可以在此事件中设置所有代码并访问发件人中的项目。
代码:
<ListBox Grid.Row="1" Grid.Column="1" Margin="10,10,0,0" x:Name="lstBank" Style="{StaticResource TransparentListBox}" ItemTemplate="{StaticResource BankDataTemplate}"
MinHeight="35" MaxHeight="220" SelectionMode="Single" ItemsSource="{Binding Path=Banks}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="lstBank_SelectionChanged" />
并在类文件中设置代码。
private void lstBank_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
}
答案 1 :(得分:1)
我终于设法做了我想要的事情,我离开了以前的上下文菜单,并且能够在ContextMenu中的MenuItems的事件处理程序中使用以下代码获取项目
if(resultsView.SelectedIndex>-1)
{
SearchFolder selectedItem;
selectedItem = (SearchFolder)resultsView.SelectedItem;
//do stuff with selectedItem
}
答案 2 :(得分:0)
在点击事件处理程序上尝试此操作:
private void ItemRightClick(object sender, EventArgs e)
{
MenuItem item = sender as MenuItem;
if (item!= null)
{
ContextMenu contextMenu = item.Parent;
Control clickedControl = contextMenu.SourceControl;
}
}
没有检查过......
无论如何,另一种方法是使用&#39; MouseDown&#39;事件并检查点击的按钮是否正确:
private void ItemMouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
ListViewItem item = listView.GetItemAt(e.X, e.Y);
if(item != null)
{
// here we have
}
}
}