In this post we saw the way to drop files in a WPF window, now we are going to see a way to drag and drop items between listboxes. Lets say tha we have 2 listboxes in a window and we like to take items from the first one and drop them in the second one. So, i think it’s time for some coding…open visual studio, create a new WPF project and add 2 listboxes like the following ones:
<ListBox Name="List1" Width="150" HorizontalAlignment="Left"> <ListBoxItem>1</ListBoxItem> <ListBoxItem>2</ListBoxItem> <ListBoxItem>3</ListBoxItem> <ListBoxItem>4</ListBoxItem> <ListBoxItem>5</ListBoxItem> </ListBox> <ListBox Name="List2" Width="150" HorizontalAlignment="Right" />
Now, we have created the 2 listboxes in which the left one, in the window, contains the items to be dragged and the right one the items to be dropped. We must handle 3 situations:
In order to handle the 1st situation we must handle the PreviewMouseLeftButtonDown event of the first listbox and if the the mouse hits a listbox item, then the drag operation proceeds. Create a handler for the first listbox’s PreviewMouseLeftButtonDown event. Now the first listbox should look like this:
<ListBox Name="List1" Width="150" HorizontalAlignment="Left" PreviewMouseLeftButtonDown="List1_PreviewMouseLeftButtonDown"> <ListBoxItem>1</ListBoxItem> <ListBoxItem>2</ListBoxItem> <ListBoxItem>3</ListBoxItem> <ListBoxItem>4</ListBoxItem> <ListBoxItem>5</ListBoxItem> </ListBox>
In the window’s code behind class add the following private variable:
private ListBoxItem _dragged;
In the handler function add the following code:
private void List1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (_dragged != null) return;
UIElement element = List1.InputHitTest(e.GetPosition(List1)) as UIElement;
while (element != null) { if (element is ListBoxItem) { _dragged = (ListBoxItem)element; break; } element = VisualTreeHelper.GetParent(element) as UIElement; } }
In this procedure, we get the exact element that is pointed by the mouse pointer and search its parents until the listbox item object is found. If no such object is found, then the drag operation doesn’t proceeds.
Now, it’s time to handle the 2nd situation. The item to be dragged has been chosen and we must do the drag operation. In order to handle this we must handle the MouseMove event of the window, so add a handler function for it:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" MouseMove="Window_MouseMove">
and in the handler function add the following code:
private void Window_MouseMove(object sender, MouseEventArgs e) { if (_dragged == null) return; if (e.LeftButton == MouseButtonState.Released) { _dragged = null; return; }
DataObject obj = new DataObject(DataFormats.Text, _dragged.ToString()); DragDrop.DoDragDrop(_dragged, obj, DragDropEffects.All); }
In this procedure, if an item is dragged and the left mouse button is still pressed, then do drag operation for the currently dragged listbox item.
And now, it’s time to handle tha 3rd and final situation. We must let the right list to allow drop and handle the appropriate drop events. Change the list’s AllowDrop property value to True and create handler functions for the DragEnter, DragOver and Drop events:
<ListBox Name="List2" Width="150" HorizontalAlignment="Right" AllowDrop="True" DragEnter="List2_DragEnter" DragOver="List2_DragEnter" Drop="List2_Drop"/>
add the following code to the List2_DragEnter function:
private void List2_DragEnter(object sender, DragEventArgs e) { if (_dragged == null || e.Data.GetDataPresent(DataFormats.Text, true) == false) e.Effects = DragDropEffects.None; else e.Effects = DragDropEffects.All; }
The only accepted dropped item is the first list’s dragged text item. Add the following code to the Drop event’s handler function:
private void List2_Drop(object sender, DragEventArgs e) { List1.Items.Remove(_dragged); List2.Items.Add(_dragged); }
The dragged item is removed from the left list and is added to the right list.
Run the application and try some drag and drops to test it. See you next time !!
Pingback from Twitted by studentguru
Pingback from Twitter Trackbacks for WPF: Drag and drop between listboxes - Development Romance [studentguru.gr] on Topsy.com
Pingback from ACCIDENTAL BREAK, HEADMAN IN DRAG, NAME GAME, THE GENTLE TOUCH | Uncategorized | Articles about Career Training !
Pingback from Dew Drop – Weekend Edition – July 31-August 1, 2010 | Alvin Ashcraft's Morning Dew
Pingback from Samsung Tocco Review – for People Who Need Great Features Right at Their Fingertips | Samsung Phone Review
Pingback from Golf Game Simulators, Golf Traning, Golf Learning
Pingback from How To Make a Advanced anti-virus(BEST) | Rid of Spyware
You dont believe, I was thinking of writing this one and just found that u did the same.
Cheers.
awesome post, really helped me with my project :)
thanks for the great article, I would like to add the Ironpython wpf drag and drop code for this:
import wpf
from System.Windows.Input import MouseButtonState
from System.Windows import Application, Window, DataObject,DataFormats,DragDrop,DragDropEffects
from System.Diagnostics import Debug
from System.Windows.Controls import *
from System.Windows.Media import VisualTreeHelper
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'dnd_02.xaml')
self._dragged = ""
def List1_PreviewMouseLeftButtonDown(self,sender,event):
element = self.List1.InputHitTest(event.GetPosition(self.List1))
while element != None:
if type(element) is ListBoxItem:
self._dragged = element
Debug.WriteLine(self._dragged.Content)
break
element = VisualTreeHelper.GetParent(element)
def Window_MouseMove(self,sender, e):
if self._dragged is None:
return
if (e.LeftButton == MouseButtonState.Released):
self._dragged = None;
obj = DataObject(DataFormats.Text, self._dragged.ToString())
DragDrop.DoDragDrop(self._dragged, obj, DragDropEffects.All)
def List2_DragEnter(self,sender, e):
if self._dragged is None or e.Data.GetDataPresent(DataFormats.Text, True) == False:
e.Effects = DragDropEffects.None
else:
e.Effects = DragDropEffects.All
def List2_Drop(self, sender, e):
self.List1.Items.Remove(self._dragged)
self.List2.Items.Add(self._dragged)
if __name__ == '__main__':
Application().Run(MyWindow())
Cheap NFL,NBA,MLB,NHL [url=http://www.annajerseys.com/]Wholesale Jerseys From China[/url].[url=http://www.annajerseys.com/]China Jerseys[/url],[url=http://www.annajerseys.com/]Sports Jerseys China[/url],[url=www.annajerseys.com/nfl-jerseys-c-1.html]NFL Jerseys China[/url],NBA Jerseys,NHL Jerseys,NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[/pre]
[pre]
We Are Professional China Brand Wholesaler,[url=www.anna-wholesale.com/brand-shoes-c-380.html]Wholesale Brand Shoes[/url],Handbags,[url=www.anna-wholesale.com/sports-jerseys-c-379.html]Sports Jerseys China[/url],Jewelry,Hats,[url=www.anna-wholesale.com/sunglasses-c-382.html]Sunglasses From China[/url],Cheap [url=http://www.anna-wholesale.com/]China Wholesael[/url],Wholesale From China,Free Shipping,Cheap Price,7 Days Deliver
Best Converse Online Store From UK,Sale 2011 Newest [url=http://www.sale-converse.com/]Converse All Stars[/url],[url=www.sale-converse.com/converse-flag-shoes-c-130.html]Converse Flag Shoes[/url],Black Converse,White Converse,Navy Converse And So on,[url=http://www.sale-converse.com/]Converse UK[/url],Free Shipping
We are professional jerseys manufacturer from china,wholesal sports jerseys From China,[url=www.anna-jersey.com/nfl-jerseys-c-773.html]NFL jerseys China[/url],[url=www.anna-jersey.com/nhl-jerseys-c-882.html]NHL Jerseys China[/url],[url=www.anna-jersey.com/nba-jerseys-c-821.html]NBA Jerseys China[/url],[url=www.anna-jersey.com/mlb-jerseys-c-694.html]MLB Jerseys China[/url],[url=http://www.anna-jersey.com/]China Jerseys[/url],Free Shipping
[url=http://www.fitflop-uk.com/]fitflops sale UK[/url] [url=http://www.fitflop-uk.com/]fitflop sale[/url]
[url=http://www.china4jersey.com/]Wholesale Jerseys From China[/url],[url=http://www.china4jersey.com/]Wholesale Jerseys[/url],[url=http://www.china4jersey.com/]China Jerseys[/url],NFL Jerseys China Paypal,NHL Jerseys China Paypal,Chinese Jerseys factory,Sewn On Jerseys,Accept Paypal,Free Shipping