我有一个网格,上面有两列。左列是 TreeView,右列是 TextBox。现在我希望能够将一个项目从 TreeView 拖到 TextBox 并且所选 TreeViewItem 的标题应该附加到文本中。我在网上搜索了很多“控件之间的拖放”,但所有这些都对我不起作用。
我的实际代码是:
private Point startPoint;
private void tvPreviewLeftMouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null);
}
private void tvPreviewMouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Released)
return;
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)
{
TreeView treeView = sender as TreeView;
TreeViewItem treeViewItem = FindAnchestor<TreeViewItem>((DependencyObject)e.OriginalSource);
object val = treeView.ItemContainerGenerator.ItemFromContainer(treeViewItem);
DataObject dragData = new DataObject("myFormat", treeViewItem.Header);
DragDrop.DoDragDrop(treeViewItem, dragData, DragDropEffects.Move);
}
}
private static T FindAnchestor<T>(DependencyObject current)
where T : DependencyObject
{
do
{
if (current is T)
return (T) current;
current = VisualTreeHelper.GetParent(current);
} while (current != null);
return null;
}
private void frtbDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
var val = (string) e.Data.GetData("myFormat");
}
}
private void frtbDragEnter(object sender, DragEventArgs e)
{
if(!e.Data.GetDataPresent("myFormat") || sender == e.Source)
e.Effects = DragDropEffects.None;
}
相应的 XAML 是:
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TreeView Grid.Column="0" x:Name="treeview" PreviewMouseLeftButtonDown="tvPreviewLeftMouseDown" PreviewMouseMove="tvPreviewMouseMove"/>
<TextBox Grid.Column="1" AllowDrop="True" Drop="frtbDrop" DragEnter="frtbDragEnter"/>
</Grid>
如果我调试它,方法tvPreviewMouseMove工作正常。DataObject 已创建并获得正确的值。但是 drop- 和 dragenter- 事件永远不会被触发。这里有什么问题?