0

我是 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);

任何想法?

4

1 回答 1

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
    }
}        

GetParentOfTypestatic 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);
}
于 2013-08-20T16:01:54.927 回答