WPF上一个简洁的DragDrop测试(例子)

来源:互联网 发布:山西大学教务网络 编辑:程序博客网 时间:2024/04/30 14:06

需要一个类似拖放的功能,看到了网上《Very Simple WPF Drag and Drop Sample without Win32 Calls》的例子,写的很简洁,故转载到这里来,方便以后查询!

这个例子只有三个源文件Shape.cs,  Windows1.xaml,  Windows1.xaml.cs。在VS2010环境下测试通过。

下面是源码清单

// copyright Nick Polyak 2008using System;using System.Collections.Generic;using System.Collections.ObjectModel;namespace DragDropTest{    // object behind the List Items (ItemsSource of the list is set to    // a collection of Shape objects)    public class Shape    {        string _name = null;        string _numSides = null;        public Shape()        {        }        public Shape(string name, string description)        {            this._name = name;            this._numSides = description;        }        public string Name        {            get            {                return _name;            }            set            {                _name = value;            }        }        public string NumSides        {            get            {                return _numSides;            }            set            {                _numSides = value;            }        }    }    // Collection of Shape objects    public class Shapes : ObservableCollection<Shape>    {        public Shapes()        {            Add(new Shape("Circle", "0"));            Add(new Shape("Triangle", "3"));            Add(new Shape("Rectangle", "4"));            Add(new Shape("Pentagon", "5"));        }    }}


 

<!--Copyright Nick Polyak 2008--><Window x:Class="DragDropTest.Window1"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:local="clr-namespace:DragDropTest"        Title="Simple WPF Drag Drop Test"        Height="300"         Width="300">    <Window.Resources>        <local:Shapes x:Key="MyShapes"/>    </Window.Resources>    <Grid>        <ListView Name="ListView1"                  ItemsSource="{Binding Source={StaticResource MyShapes}}"                  SelectionMode="Extended"                  AllowDrop="True">            <ListView.ItemTemplate>                <DataTemplate>                    <StackPanel AllowDrop="True" Orientation="Horizontal">                        <TextBlock Text="Shape Name:  "/>                        <TextBlock Text="{Binding Path=Name}"/>                        <TextBlock Text=".    Number of Sides:  "/>                        <TextBlock Text="{Binding Path=NumSides}"/>                    </StackPanel>                </DataTemplate>            </ListView.ItemTemplate>            <ListView.ItemsPanel>                <ItemsPanelTemplate>                    <StackPanel/>                </ItemsPanelTemplate>            </ListView.ItemsPanel>                        </ListView>            </Grid></Window>


 

// Copyright Nick Polyak 2008using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.Windows.Controls.Primitives;namespace DragDropTest{    // delegate for GetPosition function of DragEventArgs and    // MouseButtonEventArgs event argument objects. This delegate is used to reuse the code    // for processing both types of events.    delegate Point GetPositionDelegate(IInputElement element);    /// <summary>    /// Interaction logic for Window1.xaml    /// </summary>    public partial class Window1 : Window    {        int oldIndex = -1;        public Window1()        {            InitializeComponent();            ListView1.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(ListView1_PreviewMouseLeftButtonDown);            ListView1.Drop += new DragEventHandler(ListView1_Drop);        }        // function called during drop operation        void ListView1_Drop(object sender, DragEventArgs e)        {            if (oldIndex < 0)                return;            int index = this.GetCurrentIndex(e.GetPosition);            if (index < 0)                return;            if (index == oldIndex)                return;            Shapes myShapes = Resources["MyShapes"] as Shapes;            Shape movedShape = myShapes[oldIndex];            myShapes.RemoveAt(oldIndex);            myShapes.Insert(index, movedShape);        }        void ListView1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)        {            oldIndex = this.GetCurrentIndex(e.GetPosition);            if (oldIndex < 0)                return;            ListView1.SelectedIndex = oldIndex;            Shape selectedItem = this.ListView1.Items[oldIndex] as Shape;            if (selectedItem == null)                return;            // this will create the drag "rectangle"            DragDropEffects allowedEffects = DragDropEffects.Move;            if (DragDrop.DoDragDrop(this.ListView1, selectedItem, allowedEffects) != DragDropEffects.None)            {                // The item was dropped into a new location,                // so make it the new selected item.                this.ListView1.SelectedItem = selectedItem;            }        }        ListViewItem GetListViewItem(int index)        {            if (ListView1.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)                return null;            return ListView1.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;        }        // returns the index of the item in the ListView        int GetCurrentIndex(GetPositionDelegate getPosition)        {            int index = -1;            for (int i = 0; i < this.ListView1.Items.Count; ++i)            {                ListViewItem item = GetListViewItem(i);                if (this.IsMouseOverTarget(item, getPosition))                {                    index = i;                    break;                }            }            return index;        }        bool IsMouseOverTarget( Visual target, GetPositionDelegate getPosition){Rect bounds = VisualTreeHelper.GetDescendantBounds( target );Point mousePos = getPosition((IInputElement) target);return bounds.Contains( mousePos );}    }}


 

原创粉丝点击