我是WPF的新手,我正在尝试用旋转木马拖放。
首先,我看过listview的一个例子。例如:http://wpftutorial.net/DragAndDrop.html,我已经尝试过了,这是正确的。
但我的问题是,当我想要使用Carousel时,我不知道当我在要移动的元素中点击时选择该项目。在这个例子中是这个函数:
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);
}
}
我在xaml文件中使用此代码:
<dxca:CarouselItemsControl x:Name="_carouselName"
PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown"
PreviewMouseMove="List_MouseMove" >
我需要获取我想要拖动的对象,在示例中是联系。
// Find the data behind the ListViewItem
Contact contact = (Contact)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);
有什么想法吗?
答案 0 :(得分:1)
如果你是WPF的新手并且你正在尝试像这样棘手的东西,那么你要么非常聪明,要么......非常......还有别的。
尝试这样的事情:
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
是我创建的static extension
辅助方法:
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);
}