WPF MVVM:找出单击了哪个标题上下文菜单
我正在尝试使用 MVVM 模式来编写 WPF 应用程序。 我正在使用 WPF 数据网格(来自工具包),它缺乏自动过滤功能。 所以我想实现它。 我已经在列标题模板中添加了一个上下文菜单,它有一个名为“Filter”的 MenuItem,它实际上应该调用过滤方法。
因此,我将 MenuItem 的命令设置为转到 ViewModel 的适当 DelegateCommand。 问题是我需要传递有关已右键单击的实际列的信息! 如果我没有使用 MVVM,我将实现一个事件处理程序,它将接收“发送者”参数(MenuItem),然后我会找到它的父项(ContextMenu),然后它的父项会给我该列。 但我怎样才能在这里实现同样的目标呢? 如何将发件人传递给我的命令? 可以使用 CommandParameter 来完成此操作吗?
我真的不想使用额外的复杂模式来完成如此简单的任务。 毕竟,MVVM 应该简化开发,而不是相反......
I am trying to use the MVVM pattern to write a WPF application. I am using WPF data grid (from the toolkit) which lacks the autofiltering feature. So I want to implement it. I've added a context menu to the column header template, it has MenuItem called "Filter" which should actually call the filtering method.
So I've set a MenuItem's command to be the appropriate DelegateCommand which goes to the ViewModel. The problem is that I need to pass the information about the actual column that has been right-clicked! If I wasn't using MVVM, I would implement an event handler which would receive a "sender" argument (the MenuItem), then I would find its parent (the ContextMenu), then its parent would give me the column. But how can I achieve the same thing here? How can I pass the sender to my command? Can this be done using ComandParameter?
I really don't want to use additional complicated patterns to achieve such a simple task. After all, MVVM should simplify the development and not vice versa...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将列标题值作为命令参数传递并使用它来获取 ViewModel 中的列详细信息吗?
Can you pass the Column header value as a Command Parameter and use that to get the Column details at the ViewModel?
您可以尝试一些相对源魔术,但如果您可以为每个标头绑定不同的 ViewModel(例如 HeaderViewModelItem),那么对您来说可能会更容易。 从那里,您只需在 HeaderViewModelItem 中触发 DelegateCommand,而不是在较大的视图模型上。
我使用这个模型并取得了相当成功。 绕过一些数据绑定舞蹈。
You could try some relative source magic, but it might be easier on you if you can have a different ViewModel that you bind to for each header, like HeaderViewModelItem. From there you'd just be firing a DelegateCommand in your HeaderViewModelItem, rather on your larger viewmodel.
I've used this model with pretty good success. Gets around a little bit of databinding dance.
如果您想将某些内容传递到命令参数中,请务必注意上下文菜单位于其自己的可视化树上。 幸运的是,它仍然从其父级继承 DataContext,因此类似的内容
应该为您提供 GridViewColumnHeader,或者至少是其可视化树中的某些内容。
If you want to pass something into the command parameter it is important to note that a context menu is on its own visual tree. Luckily it still inherits the DataContext from its parent, so something like
should get you the GridViewColumnHeader, or at least something in the visual tree of it.