简体   繁体   English

使用上下文菜单后获取选定的 ListView 项目

[英]Get selected ListView item after using Context Menu

I'm coding a simple music player in WPF with ListView containing my mp3 files.我正在使用包含我的 mp3 文件的 ListView 在 WPF 中编写一个简单的音乐播放器。 After MouseDoubleClick I get selected item this way:在 MouseDoubleClick 之后,我以这种方式获得选定的项目:

private void PlayNow(object sender, EventArgs e)
{
   var item = (sender as ListView).SelectedItem;
   if (item != null)
   {
       //Some code here
   }
}

But when I do the same via ContextMenu, my selected item is ContextMenu.Item.但是当我通过 ContextMenu 执行相同操作时,我选择的项目是 ContextMenu.Item。 I still need the ListView selected item tho.我仍然需要 ListView 选定的项目。 How can I get it via ContextMenu?如何通过 ContextMenu 获取它?

You can access the item the ContextMenu belongs to using the PlacementTarget property.您可以使用PlacementTarget属性访问ContextMenu所属的项目。

If you want to do this the "proper" way, though, I might suggest reading up on commands .但是,如果您想以“正确”的方式执行此操作,我可能会建议您阅读commands You could bind both the double-click action and the ContextMenu 's item to MediaCommands.Play , and pass the corresponding item by binding it to CommandParameter .您可以将双击操作和ContextMenu的项目都绑定到MediaCommands.Play ,并通过将其绑定到CommandParameter来传递相应的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM