如何在不违反 MVVM 原则的情况下处理拖放?
目前,我的 XAML 中
<TabControl
AllowDrop="True"
PreviewDragOver="DragOver"
PreviewDrop="Drop" />
所有拖/放代码都存在于视图的代码隐藏中,而不是在 ViewModel 中。
如何在 ViewModel 中处理拖放而不添加对 View 的任何依赖项?
Currently I have in my XAML
<TabControl
AllowDrop="True"
PreviewDragOver="DragOver"
PreviewDrop="Drop" />
All of my drag/drop code exists within the codebehind of my View, rather than within my ViewModel.
How can I handle drag/drop in my ViewModel without adding any dependencies on the View?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有一些库可以实现此目的,例如 gong 以及各种博客文章中的类似片段。
然而,您不应该太执着于完全没有代码隐藏。例如,这仍然是我书中的 MVVM:
命令绑定可能是更好的选择,但逻辑肯定在视图模型中。借助拖放之类的功能,您想要绘制界限的位置变得更加可变。您可以在适当的时候让代码隐藏解释拖动参数并调用视图模型上的方法。
There are libraries for this such as gong and similar snippets on various blog articles.
However, you shouldn't get too hung up on having absolutely no code-behind. For example, this is still MVVM in my book:
A command binding might be a better choice, but the logic is definitely in the viewmodel. With something like Drag and Drop, it's more variable where you want to draw the line. You can have code-behind interpret the Drag Args and call methods on the viewmodel when appropriate.
下面是我编写的一些代码,允许您将文件拖放到控件上而不违反 MVVM。可以轻松修改它以传递实际对象而不是文件。
用法:
确保DataContext继承自IFileDragDropTarget并实现OnFileDrop。
Here is some code I wrote that allows you to drag and drop files onto a control without violating MVVM. It could easily be modified to pass the actual object instead of a file.
Usage:
Ensure the DataContext inherits from IFileDragDropTarget and implements the OnFileDrop.
这是一个比 Mustafa 的解决方案更通用、开箱即用、更简单的解决方案,具有单个 DependencyProperty
快乐滴!
Here is a solution a bit more generic, out-of-the-box and easier than Mustafa's one, with a single DependencyProperty
Happy drops !
这只是一个附加答案,将 @Asheh 的答案移植到 VB.NET 供 VB 开发人员使用。
This is just an additional answer that ports @Asheh's answer's to VB.NET for VB developers.
这也可能对您有一些帮助。附加的命令行为库允许您将任何事件转换为更紧密地遵循 MVVM 框架的命令。
http://marlongrech.wordpress.com/2008/12/ 13/attachedcommandbehavior-v2-aka-acb/
使用它非常简单。并多次保存了我的培根
希望这有帮助
This might also be of some help to you. The attached command behavior library allows you to convert any event(s) into a command which will more closely adhere to the MVVM framework.
http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/
Using this is extremely easy. And has saved my bacon numerous times
Hope this helps
根据@Kino101的回答,我创建了一个WinUI 3版本。它也可以作为 要点 提供。
Helpers/DropFilesBehaviour.cs
在 ViewModel 中的使用,例如
ViewModels/MainViewModel.cs
在视图中的使用,例如
Views/MainPage.xaml
Based on @Kino101's answer, I created a WinUI 3 version. It is also available as a gist.
Helpers/DropFilesBehaviour.cs
Usage in your ViewModel, e.g.
ViewModels/MainViewModel.cs
Usage in your view, e.g.
Views/MainPage.xaml