יום חמישי, 17 במרץ 2011

WPF - DRAG&DROP objects in ListBox

I would like to show example of how to drug and drop objects between different ListBox.
All starting with Mouse PreviewMouseLeftButtonDown Event and finished (more important) with GarageEntryListBox_Drop (see below).


private void GarageEntryListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {           
            ListBox parent = (ListBox)sender;
            Point point  = e.GetPosition(parent) ;
            UIElement element = parent.InputHitTest(point) as UIElement;            
            UIElement panel = GetParent<GarageEntryPanel>(element, parent);
            object data = GetDataFromListBox(parent, panel);           
            if (data != null)
            {
                DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
            }
        }
 
        private object GetDataFromListBox(ListBox source, UIElement element)
        {
            UIElement result = GetParent<GarageEntryPanel>(element, source);
            return result;
        }
 
        public UIElement GetParent<TSource>(UIElement element, UIElement stopOn)
        {
 
            while (element != null && !(element is TSource) && (element != stopOn))
            {
                element = VisualTreeHelper.GetParent(element) as UIElement;               
            }
            if (element == stopOn)
                return null;
            else
                return element;
            
        }
 
        private void GarageEntryListBox_Drop(object sender, DragEventArgs e)
        {
            ListBox currentListBox = (ListBox)sender;
            GarageEntryPanel data = e.Data.GetData(typeof(GarageEntryPanel)) 
                                                           as GarageEntryPanel;
            if(data == null) 
                return;
            ListBox sourceList = GetParent<ListBox>(data, nullas ListBox;
            if (sourceList == currentListBox)
                return;
            ld_garageentry entry = data.DataContext as ld_garageentry;           
            ((IList)sourceList.ItemsSource).Remove(entry);
            ((IList)currentListBox.ItemsSource).Add(entry);                            
        }

אין תגובות:

הוסף רשומת תגובה