Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
swdev:dotnet:drag_and_drop [2010/11/15 14:47] smayr |
swdev:dotnet:drag_and_drop [2011/04/06 08:44] (current) smayr |
||
---|---|---|---|
Line 13: | Line 13: | ||
< | < | ||
</ | </ | ||
+ | </ | ||
+ | Code behind: | ||
+ | <code csharp> | ||
+ | private void lstEnvironments_SelectionChanged(object sender, SelectionChangedEventArgs e) | ||
+ | { | ||
+ | string myDragData = ((ListBoxItem)lstEnvironments.SelectedItem).Content.ToString(); | ||
+ | lblSelectedEnvironment.Text = string.Format(" | ||
+ | } | ||
+ | private void lstEnvironments_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) | ||
+ | { | ||
+ | // Store the mouse position | ||
+ | startPoint = e.GetPosition(null); | ||
+ | } | ||
+ | |||
+ | private void lstEnvironments_MouseMove(object sender, MouseEventArgs e) | ||
+ | { | ||
+ | // Get the current mouse position | ||
+ | Point mousePos = e.GetPosition(null); | ||
+ | Vector diff = startPoint - mousePos; | ||
+ | |||
+ | if (e.LeftButton == MouseButtonState.Pressed && | ||
+ | Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance && | ||
+ | Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance) | ||
+ | { | ||
+ | // Get the dragged ListBoxItem | ||
+ | ListBox lstBox = sender as ListBox; | ||
+ | ListBoxItem lstBoxItem = FindAnchestor< | ||
+ | |||
+ | // Find the data behind the ListBoxItem | ||
+ | //string str = (string)lstBox.ItemContainerGenerator.ItemFromContainer(lstBoxItem); | ||
+ | string str = ((ListBoxItem)lstBox.SelectedItem).Content.ToString(); | ||
+ | |||
+ | // Initialize the drag & drop operation | ||
+ | DataObject dragData = new DataObject(typeof(string), | ||
+ | DragDrop.DoDragDrop(lstBoxItem, | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // Helper to search up the VisualTree | ||
+ | private static T FindAnchestor< | ||
+ | where T : DependencyObject | ||
+ | { | ||
+ | do | ||
+ | { | ||
+ | if (current is T) | ||
+ | { | ||
+ | return (T)current; | ||
+ | } | ||
+ | current = VisualTreeHelper.GetParent(current); | ||
+ | } | ||
+ | while (current != null); | ||
+ | return null; | ||
+ | } | ||
</ | </ | ||
Line 53: | Line 106: | ||
string str = e.Data.GetData(typeof(string)) as string; | string str = e.Data.GetData(typeof(string)) as string; | ||
ListBox lstBox = sender as ListBox; | ListBox lstBox = sender as ListBox; | ||
- | lstBox.BeginInit(); | ||
lstBox.Items.Add(str); | lstBox.Items.Add(str); | ||
- | lstBox.EndInit(); | ||
} | } | ||
} | } | ||
Line 80: | Line 131: | ||
== Resources == | == Resources == | ||
* [[http:// | * [[http:// | ||
- | * [[http:// | + | * [[http:// |
* [[http:// | * [[http:// | ||
* [[http:// | * [[http:// | ||
+ | * [[http:// | ||
+ | * [[http:// |