如何在按钮的 CommandParam 中传递特定的视图模型对象?
我有一个使用主从 UI 模式的简单 WPF 程序,其中详细信息显示主窗格中当前选定的集合项目。 我使用的是 MVVM,每个 XAML 页面都由一个 ViewModel 对象支持,该对象设置为 DataContext。
现在,我想在“主”窗格中添加一个“删除”按钮,以从主项目列表中删除。 但是,我不知道如何将当前所选项目的视图模型对象作为按钮 CommandParameter 传递给路由命令处理程序代码。
预先感谢您的任何指点。
麦克风
I have a simple WPF program using the Master-Detail UI pattern, where the Detail shows the currently selected item of a collection in the Master pane. I'm using MVVM, and each XAML page is backed by a ViewModel object which is set as it's DataContext.
Now, I want to add a DELETE button in the Master pane to delete from the master list of items. However, I can't figure out how to pass the viewmodel object of the currently selected item as a button CommandParameter to the routed command handler code.
Thanks in advance for any pointers.
Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与 Paul 所展示的类似的是,您的视图模型将知道当前选择了哪个项目。 即,
您的 XAML 可以很简单
只要您的主窗格在选择它时设置 CurrentItem 属性,您的命令就可以简单地将 CurrentItem 设置为命令参数。
Something similiar to what Paul has shown is where your view model will know which item is currently selected. I.e.
Your XAML can then be simply
As long as your master pane sets the CurrentItem property when you select it, your command can simple have the CurrentItem set as the command parameter.
一种选择是创建每个命令并引用视图模型,并在视图模型上创建一个绑定到当前所选项目的属性。 这样您就不需要将所选项目作为参数传递 - 该命令可以从虚拟机中检索它。 如果这不适合您的情况,您可以传递选定的项目,如下所示:
其中 listBox_ 是从 Selector 派生的控件。
希望有帮助,
保罗
One option would be to create each command with a reference to the view model, and create a property on the view model which is bound to the currently selected item. This way you don't need to pass the selected item as a parameter - the command can retrieve it from the VM. If this isn't suitable for your circumstances, you could pass the selected item something like this:
Where listBox_ is a control which derives from Selector.
Hope that helps,
Paul