【问题标题】:Binding a command and DragEnter and Drop events in the same button in WPF在 WPF 中的同一按钮中绑定命令和 DragEnter 和 Drop 事件
【发布时间】:2017-12-27 07:30:38
【问题描述】:

在我的 WPF MVVM (NET 3.5) 应用程序中,我有以下按钮:

<Button AllowDrop="True"  
        Drop="btnDelete_Drop" 
        DragEnter="btnDelete_DragEnter"
        Content="Delete"/>

按钮行为如下:

  • 如果在此按钮上拖放某些列表视图项目,则会引发视图中的某些事件 btnDelete_DragEnter" 和 "btnDelete_Drop"。在放置时,通过从视图调用视图模型中的方法来删除放置的项目。

现在,我想控制按钮上的单击事件,并且我想只对这个事件使用命令。

所以我的问题是:

有没有什么方法可以通过 Drop 和 DragEnter 事件来关联一个只针对 click 事件的命令并保持上面的其余事件?

似乎可以通过导入以下参考来使用 Prism(参见here)来完成:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

但我的问题是它与 WPF .NET 3.5 不兼容......所以在不使用 Prism 的情况下还有其他方法吗?

【问题讨论】:

    标签: c# wpf mvvm command icommand


    【解决方案1】:

    有没有什么方法可以通过 Drop 和 DragEnter 事件来关联一个只针对 click 事件的命令并保持上面的其余事件?

    是的。这正是ButtonCommand 属性的用途。将此属性绑定到您的视图模型的 ICommand 属性:

    <Button Command="{Binding YourCommandProperty}" />
    

    您需要实现ICommand 接口。 Prism 提供了一种称为DelegateCommand 的方法,但您可以定义自己的一种。请参阅以下博客文章了解更多信息:https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/。它包括一个示例实现。

    【讨论】:

    【解决方案2】:

    当然,你可以使用 Command 属性....

    <Button AllowDrop="True"  
            Drop="btnDelete_Drop" 
            DragEnter="btnDelete_DragEnter"
            Command="{Binding ClickCommand}"
            Content="Delete"/>
    

    并在您的 ViewModel 中实现一个名为 ClickCommand 的 ICommand

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多