How to Drag and drop the content of an Item from WPF comboBox to WPF TextBox
I am using following WPF Code
<ComboBox Name="cmbFunctionsList" Grid.Row="3" Grid.Column="1"
DropDownClosed="OnCmbFunctionsListDropDownClosed"
DisplayMemberPath="FunctionItem" SelectedValuePath="FunctionValue"
PreviewMouseLeftButtonDown="OnFunctionsListPreviewMouseLeftButtonDown"
PreviewMouseMove="OnFunctionsListPreviewMouseMove"
MinHeight="25" Margin="2,2,2,0" VerticalAlignment="Center"/>
<TextBox Grid.Column="1" Margin="2" Grid.Row="2" Grid.ColumnSpan="2" Name="txtExpression"
AllowDrop="True" Drop="OnTxtExpressionDrop" DragEnter="OnTxtExpressionDragEnter" />
private vo开发者_如何学JAVAid OnFunctionsListPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//storing the mouse position
_startPoint = e.GetPosition(null);
}
private void OnFunctionsListPreviewMouseMove(object sender, MouseEventArgs e)
{
// Drag and Drop Code is commented
// 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)
{
ComboBox cmb = sender as ComboBox;
cmb.StaysOpenOnEdit = true;
ComboBoxItem cmbItem = FindAnchestor<ComboBoxItem>((DependencyObject)e.OriginalSource);
if (cmbItem != null)
{
if (cmbFunctionsList.SelectedIndex > -1 && cmbFunctionsList.IsDropDownOpen == true)
{
// Find the data behind the ComboBoxItem
DataRowView dr = (DataRowView)cmb.ItemContainerGenerator.ItemFromContainer(cmbItem);
string draggedText = (String)dr[1];
// Initialize the drag & drop operation
DataObject dragData = new DataObject("stringFormat", draggedText);
DragDrop.DoDragDrop(cmbItem, dragData, DragDropEffects.Copy);
}
}
}
}
private void OnTxtExpressionDragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("stringFormat") || sender == e.Source)
{
e.Effects = DragDropEffects.Copy;
}
}
private void OnTxtExpressionDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("stringFormat"))
{
String droppedText = e.Data.GetData("stringFormat") as String;
TextBox txtExp = sender as TextBox;
txtExp.Text = droppedText;
}
}
but still the Drag and drop functionality is not working . Moreover when I try to drag an item from comboBox it is getting closed automatically.
Can you suggest to me what I am missing here?
Drop event is automatically handled in WPf so need not to write the event Drop or Preview Drop
精彩评论