I´m new in WPF and I´m trying to do a drag and drop with carousel.
First, I´ve seen a example with listview. The example is this: http://wpftutorial.net/DragAndDrop.html , I´ve tried it and it is correct.
But my problem is that when I want to use a Carousel I don´t know to get the item selected when I do a click in the element I want to move. In the example is this function:
private void List_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 ListViewItem
ListView listView = sender as ListView;
ListViewItem listViewItem =
FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);
// Find the data behind the ListViewItem
Contact contact = (Contact)listView.ItemContainerGenerator.
ItemFromContainer(listViewItem);
// Initialize the drag & drop operation
DataObject dragData = new DataObject("myFormat", contact );
DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move);
}
}
I´m using this code in xaml file:
<dxca:CarouselItemsControl x:Name="_carouselName"
PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown"
PreviewMouseMove="List_MouseMove" >
I need to get the object I want to drag, in the example is contact.
// Find the data behind the ListViewItem
Contact contact = (Contact)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);
Any idea?
If you're new to WPF and you're attempting something as tricky as this, then you're either very clever or very... well... something else.
Try something like this:
private void ListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UIElement uiElement = (UIElement)e.Source;
HitTestResult hitTestResult = VisualTreeHelper.HitTest(uiElement,
e.GetPosition(null));
ListBoxItem listBoxItemUnderMouse = hitTestResult.VisualHit.
GetParentOfType<ListBoxItem>();
if (listBoxItemUnderMouse != null)
{
// Do your stuff here
}
}
GetParentOfType
is a static extension
helper method that I created:
public static T GetParentOfType<T>(this DependencyObject element) where T : DependencyObject
{
Type type = typeof(T);
if (element == null) return null;
DependencyObject parent = VisualTreeHelper.GetParent(element);
if (parent == null && ((FrameworkElement)element).Parent is DependencyObject)
parent = ((FrameworkElement)element).Parent;
if (parent == null) return null;
else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type)) return
parent as T;
return GetParentOfType<T>(parent);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.