拖拽的实现

实现效果:左键自定义控件上的树节点,将信息拖拽到主窗体的文本框中

 

自定义控件: ----拖拽源

.cs中

View Code
private void OnPreviewListBoxMouseMove(object sender, MouseEventArgs e)
{
Point pos = e.GetPosition(leftDataTree); //获取mListBox位置
HitTestResult result = VisualTreeHelper.HitTest(leftDataTree, pos); //获取mListBox信息
TreeViewItem listBoxItem = Utils.FindVisualParent<TreeViewItem>(result.VisualHit); //找到实际要拖拽的
if (listBoxItem == null || listBoxItem.DataContext != leftDataTree.SelectedItem || !(leftDataTree.SelectedItem is DataTreeModel))
return;
if (((DataTreeModel)listBoxItem.DataContext).Parent == null)
return;
#region 复制效果
//DragDropAdorner adorner = new DragDropAdorner(listBoxItem);
//mAdornerLayer = AdornerLayer.GetAdornerLayer(mTopLevelGrid);
//mAdornerLayer.Add(adorner);
#endregion

DataTreeModel dataItem = listBoxItem.DataContext as DataTreeModel;
DataObject dataObject = new DataObject(dataItem);
System.Windows.DragDrop.DoDragDrop(leftDataTree, dataObject, DragDropEffects.Copy);

//mAdornerLayer.Remove(adorner); //复制完后删除效果
}
View Code
    internal static class Utils
    {
        /// <summary>
        /// 复制
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FindVisualParent<T>(DependencyObject obj) where T : class
        {
            while (obj != null)
            {
                if (obj is T)
                    return obj as T;
                obj = VisualTreeHelper.GetParent(obj);
            }
            return null;
        }
    }

 

.xaml中

  <TreeView Height="700"  HorizontalAlignment="Left" x:Name="leftDataTree"  
                  VerticalAlignment="Top" Width="200" ItemsSource="{Binding DataTreeNode}" SelectedItemChanged="leftDataTree_SelectedItemChanged" >

 

主窗体:  ----接收数据

.cs中

View Code
        private void OnDragOver(object sender, DragEventArgs e)
        {
            e.Handled = true;
            e.Effects = DragDropEffects.Copy; 
        }

 

.xaml中

   <TextBox Name="txtinfo" TextWrapping="Wrap" AllowDrop="True" PreviewDragOver="OnDragOver"/>

 

最后你会发现,其实拖拽源和接收数据是分开的,两个独立的功能块。用起来很爽。(但是有些第三方控件不支持拖拽,坑爹啊)

posted @ 2012-07-16 14:06  zhaoping  阅读(269)  评论(0编辑  收藏  举报