WPF 上下文菜单和 ListView

发布于 2024-08-21 02:18:40 字数 442 浏览 1 评论 0原文

好吧,希望这很简单,但由于某种原因我找不到直接的答案,而且我对 WPF 还不够熟悉,还不知道如何做到这一点。

我有一个列表视图,它绑定到要显示的可观察对象集合。我想要一个包含很多选项的上下文菜单。上下文菜单中的选项与单击的列表中的特定对象相关(例如删除、导出等)。

因此,我需要将用户在列表视图中右键单击的对象作为参数传递给上下文菜单执行的命令。

我该怎么做?

编辑:我应该提到我更喜欢一个主要(如果不是完全)xaml 的解决方案 - 我试图避免在代码隐藏中包含重要的代码。如果这是唯一的方法...

进一步编辑:我忘记提及的更多细节很重要。我想要执行的命令是在绑定到我的用户控件的数据上下文的对象上执行的,而不是在列表视图中的对象上执行的。因此,我需要将列表视图项目上的上下文菜单绑定到用户控件数据上下文上的命令,并将列表视图项目作为参数传递到该命令中。

Ok, hopefully this is simple but for some reason I can't find a straight answer and I'm not familiar enough with WPF yet to know how to do it.

I have a listview, it gets bound to an observable collection of objects to display. I want to have a context menu with a bunch of options. The options in the context menu are relative to the particular object in the list that was clicked on (things like delete, export, etc).

So I need the object that the user right clicked on in my listview to be passed as a parameter to the command that the context menu executes.

How do I do this?

Edit: I should mention I would prefer a solution that is mostly (if not entirely) xaml - I'm trying to avoid having significant code in the code-behind. If that's the only way to do it though...

Further Edit: More details that I forgot to mention that are important. The command I want executed is on the object bound to the data context of my user control, it is not on the objects in the list view. So I need the context menu's on the list view's items to be bound to a command that is on the user control's data context, and the listview item passed as a parameter into that command.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

大海や 2024-08-28 02:18:40

这取决于您的 ContextMenu 是单个项目模板的一部分,还是作为一个整体附加到 ListBox。

如果您使用 DataTemplate 将 ContextMenu 附加到列表中的项目(这通常是最好的方法),则 MenuItem< 上的 DataContext /code> 已设置,因此您需要做的就是:

<MenuItem ... CommandParameter="{Binding}" />

另一方面,如果您的 ContextMenu 作为一个整体附加到 ListBox,则您需要访问 ListBoxSelectedItem 属性:

<MenuItem ... CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor,ListBox,1}} />

It depends on whether your ContextMenu is part of the template for individual items, or if it is attached to the ListBox as a whole.

If you are attaching your ContextMenu to the items in the list using a DataTemplate (this is generally the best way to do it), the DataContext on the MenuItem is already set so all you need to do is:

<MenuItem ... CommandParameter="{Binding}" />

On the other hand, if your ContextMenu is attached to the ListBox as a whole, you'll need to access the SelectedItem property of the ListBox:

<MenuItem ... CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor,ListBox,1}} />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文