第一项是从listboxdrag拖放到listboxdrop,如何使用拖放重新排列listboxdrop中的项目

时间:2016-12-08 17:21:26

标签: wpf drag-and-drop listboxitem

第一项是从listboxdrag拖放到listboxdrop,如何使用拖放重新排列listboxdrop中的项目

ListBox dragSource = null;
private void listboxdrop_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ListBox parent = (ListBox)sender;
            dragSource = parent;
            object data = GetDataFromListBox(dragSource, e.GetPosition(parent));

        if (data != null)
        {
            DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
        }
    }
#region GetDataFromListBox(ListBox,Point)
    private static object GetDataFromListBox(ListBox source, Point point)
    {
        UIElement element = source.InputHitTest(point) as UIElement;
        if (element != null)
        {
            object data = DependencyProperty.UnsetValue;
            while (data == DependencyProperty.UnsetValue)
            {
                data = source.ItemContainerGenerator.ItemFromContainer(element);
                if (data == DependencyProperty.UnsetValue)
                {
                    element = VisualTreeHelper.GetParent(element) as UIElement;
                }
                if (element == source)
                {
                    return null;
                }
            }
            if (data != DependencyProperty.UnsetValue)
            {
                return data;
            }
        }
        return null;
    }
    private void listboxdrop_Drop(object sender, DragEventArgs e)
    {
        ListBox parent = (ListBox)sender;
        object data = e.Data.GetData(typeof(string));
        ((IList)dragSource.ItemsSource).Remove(data);
        parent.Items.Add(data);
    }

XmaI位

<Grid>
        <ListBox x:Name="listboxdrag" PreviewMouseLeftButtonDown="ListBoxdrag_PreviewMouseLeftButtonDown"
                 HorizontalAlignment="Left" Margin="12,29,0,12" Width="215" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible" />
        <ListBox x:Name="listboxdrop" Drop="ListBox_Drop" AllowDrop="True"
            PreviewMouseLeftButtonDown="ListBoxdrop_PreviewMouseLeftButtonDown"     HorizontalAlignment="Right" Margin="0,29,12,12" Width="215" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible"/>
        <TextBlock Height="21" Text="ListBox One" HorizontalAlignment="Left" 
                   Margin="12,2,0,0" VerticalAlignment="Top" Width="120" />
        <TextBlock Height="21" Text="ListBox Two" HorizontalAlignment="Right" 
                   Margin="0,2,107,0" VerticalAlignment="Top" Width="120" />
    </Grid>

0 个答案:

没有答案