【问题标题】:How to view drag & drop element in WPF?如何在 WPF 中查看拖放元素?
【发布时间】:2010-12-22 20:18:57
【问题描述】:

我有一个ListBox 和一个DockPanel。列表框包含应该被拖到停靠面板上的项目。我已经按照link 实现了这一点。

虽然有几件事我不明白:

  1. 在拖动时,我看到的只是一个光标。我想文学看看我的清单项目 拖动以使用我的光标四处移动。我该怎么做?
  2. DragDropEffect 属性是否仅适用于不同的光标设计,或者它具有 更高的目的? :)
  3. 如何让列表项从ListBox 中消失 DockPanel?
  4. 我想在我拖动的项目上强制执行一些动画,比如发光后 掉了。我应该使用哪个触发器/设置器?

这是我的基本拖放代码:

ListBox 部分的代码隐藏

private Point startPosition;

private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    startPosition = e.GetPosition(null);
}

private void ListBox_PreviewMouseMove(object sender, MouseEventArgs e)
{
    Point currentPosition;
    Vector offset;
    ListBox listBox;
    ListBoxItem item;
    Match match;
    DataObject dragData;

    currentPosition = e.GetPosition(null);
    offset = startPosition - currentPosition;

    if (e.LeftButton == MouseButtonState.Pressed &&
        (Math.Abs(offset.X) > SystemParameters.MinimumHorizontalDragDistance ||
         Math.Abs(offset.Y) > SystemParameters.MinimumVerticalDragDistance))
    {
        // Get the data binded to ListBoxItem object, which is "match"
        listBox = sender as ListBox;
        item = FindAnchestor<ListBoxItem>((DependencyObject)e.OriginalSource);
        match = (Match)listBox.ItemContainerGenerator.ItemFromContainer(item);

        dragData = new DataObject("match", match);
        DragDrop.DoDragDrop(item, dragData, DragDropEffects.Move);
    }
}

DockPanel 部分的代码隐藏

private void DockPanel_DragEnter(object sender, DragEventArgs e)
{
    if (!e.Data.GetDataPresent("match") ||
        sender == e.Source)
    {
        e.Effects = DragDropEffects.None;
    }
}

private void DockPanel_Drop(object sender, DragEventArgs e)
{
    Match match;
    DockPanel matchSlot;
    ContentPresenter contentPresenter;
    Binding binding;

    if (e.Data.GetDataPresent("match"))
    {
        match = e.Data.GetData("match") as Match;
        matchSlot = sender as DockPanel;

        contentPresenter = new ContentPresenter();
        contentPresenter.ContentTemplate = this.FindResource("MatchTemplate") as DataTemplate;
        binding = new Binding();
        binding.Source = match;
        contentPresenter.SetBinding(ContentPresenter.ContentProperty, binding);

        matchSlot.Children.Clear();
        matchSlot.Children.Add(contentPresenter);
    }
}

感谢所有帮助。

【问题讨论】:

    标签: wpf drag-and-drop


    【解决方案1】:

    好的,过了一会儿,我自己找到了一些答案并发现了一些东西。

    至于DragDropEffect枚举,应该使用它有两个原因:

    1. 在代码中区分项目是移动还是复制。它就像一个标志,最常用的应该是这样的:

      如果 (e.DragDropEffect == DragDropEffect.Move)
      {
      ...
      }
      否则...

    2. 根据枚举值修饰鼠标光标。通过这种方式,它会告诉用户他或她是否正在移动或复制项目。

    至于拖放可视化,这里有一个帖子链接,其中包含参考,这是一个很好的拖放起点:WPF Drag & Drop: How to literally drag an element?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2018-09-29
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多