[英]Context Menu in ListView, choosing an Item
单击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);
}
}
}
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) {
}
我终于设法完成了我想做的事情,我像以前一样离开了上下文菜单,并且能够在ContextMenu中的MenuItems的事件处理程序中使用以下代码获取该项目
if(resultsView.SelectedIndex>-1)
{
SearchFolder selectedItem;
selectedItem = (SearchFolder)resultsView.SelectedItem;
//do stuff with selectedItem
}
在点击事件处理程序上尝试以下操作:
private void ItemRightClick(object sender, EventArgs e)
{
MenuItem item = sender as MenuItem;
if (item!= null)
{
ContextMenu contextMenu = item.Parent;
Control clickedControl = contextMenu.SourceControl;
}
}
还没有检查...
无论如何,另一种方法是使用'MouseDown'事件并检查单击的按钮是否正确:
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.