【问题标题】:Add Drag&Drop with Behaviors使用行为添加拖放
【发布时间】:2017-06-23 09:34:39
【问题描述】:

我需要修改一个使用 WPF、MVVM 和行为进行事件处理的桌面应用程序。我的任务是为按钮实现拖放。如果用户按下按钮,它将弹出一个文件保存窗口,但如果用户单击并拖动它,它应该显示一个文件图标,并让用户将其拖放到资源管理器窗口中以将其保存在那里。

我已经添加了命名空间:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:behaviors="clr-namespace:MyApplication.Desktop.Client.Behaviors"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:command="http://www.galasoft.ch/mvvmlight"

我还在按钮中添加了 XAML 代码:

<Button Grid.Column="2"
  Command="{Binding SaveAttachmentCommand}"
  Visibility="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource boolToVisibilityConverter}}" 
  Style="{StaticResource AttachmentSaveButtonStyle}">

  <i:Interaction.Triggers>
  <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
    <command:EventToCommand Command="{Binding LeftMouseButtonDownCommand}"/>
  </i:EventTrigger>
  </i:Interaction.Triggers>

  <i:Interaction.Behaviors>
    <behaviors:FrameworkElementDragBehavior>
    </behaviors:FrameworkElementDragBehavior>
  </i:Interaction.Behaviors>
</Button>

但我不知道如何告诉行为类(FrameworkElementDragBehavior)处理哪些事件以及如何处理它们(调用哪些函数)。

我已经阅读了一些教程,但我仍然感到困惑。

【问题讨论】:

    标签: c# wpf mvvm desktop-application attachedbehaviors


    【解决方案1】:

    两个月前,我不得不使用 MVVM 进行拖放。

    经过一些研究,个人认为,实现这一目标的最佳方法是使用“GongSolutions DragDrop”库。 它非常简单,非常适合您正在寻找的东西。 例如,在树视图中:

        <TreeView ItemsSource="{Binding LstCat}" 
                  dd:DragDrop.IsDragSource="True" 
                  dd:DragDrop.IsDropTarget="True"
                  dd:DragDrop.DragAdornerTemplate="{StaticResource DragAdorner}">
        //Treeview Structure
    
        </TreeView>
    

    从那里您可以在树视图中进行拖放。您也可以添加一个 dragAdorner(当您拖动某些东西时,您的指针旁边会显示一个图像)

    在 viewModel 中,您可以通过实现库附带的接口来判断拖动或放置的行为。这样您就可以访问您拖动的数据。 例如:

        public void DragOver(IDropInfo dropInfo)
        {
            if (dropInfo.Data is Category && dropInfo.TargetItem is Rubrique)
            {
                return;
            }
    
            dropInfo.DropTargetAdorner = DropTargetAdorners.Highlight;
            dropInfo.Effects = DragDropEffects.Move;
        }
    

    如果您有兴趣,这里是图书馆的链接: https://github.com/punker76/gong-wpf-dragdrop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多