命令绑定到用户控件拖/放
如何使用 WPF 中的命令模式创建响应用户控件的拖/放事件的 UI?
How can I create a UI that responds to Drag/Drop events of a usercontrol by usinng the Command pattern in WPF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在用户控件上
实现具有参数的命令。我将 ICommand 与 Josh Smiths RelayCommand 一起使用,但我对其进行了扩展以给它一个参数。 (代码在此答案末尾)
现在您可以将视图模型绑定到此命令。
为我们的实体拖动类型设置另一个属性(您可以对其进行硬编码),但我将此用户控件重用于不同的事物,并且我不希望一个控件接受拖放时的错误实体类型。
当你调用DragDrop.DoDragDrop时,重写OnPreviewLeftMouseButtonDown
,下面的方法会在适当的时候被调用
重写OnDragOver和OnDragDrop方法,并使用一个命令来询问我们是否可以拖动,我们可以
在视图模型中放置 通常您会从一个用户控件拖动到另一个用户控件
那么当您在视图模型中设置命令时,请使用类似这样的内容,然后将命令绑定到您的用户控件,
,这样您就可以为一个用户控件设置一个命令,并为一个用户控件设置一个命令对于另一个,每个都有您可以接受的不同 DragEntityType。两个用户控件,一个用于拖动,一个用于放置,反之亦然。每个用户控件都有不同的 DragEntityType,因此您可以辨别拖动源自哪一个。
当我们放下时,
我可能会错过一些东西,但是这种技术可以让我询问视图模型是否可以拖动项目,并让我询问视图模型是否可以放下(如果视图模型将接受该项目)其可绑定的,它很好地分离了视图/视图模型。如果您有任何疑问,请随时提问。
扩展中继命令,谢谢乔什史密斯......
On the User Control
Implement a command that has a parameter. I use ICommand with Josh Smiths RelayCommand, but i extend it to give it a parameter. (code at the end of this answer)
now you can bind your view model to this command.
set another property for our entity drag type (you could hard code this) but i reuse this user control for different things and i dont want one control to accept the wrong entity type on a drop.
Override the OnPreviewLeftMouseButtonDown
when you call DragDrop.DoDragDrop, the below methods will be called at the approriate time
Override the OnDragOver and OnDragDrop methods, and use a command to ask if we can drag and we can drop
In the View Model
then when you are setting up your command in the view model use something like this, then bind the command to your user control
usually you are dragging from one user control to another so you would set up one command for one user control and one for the other, each having a different DragEntityType that you would accept. Two user controls one to drag from, one to drop on, and vica versa. each user control has a different DragEntityType so you can tell which one the drag originated from.
and when we drop
I might have missed something, but this technique lets me ask the view model if i can drag an item, and lets me ask the view model if i can drop (if the view model will accept the item) its bindable, and it seperates view/ view model nicely. If you have any questions feel free to ask.
Extended Relay Command, thanks Josh Smith...