2
內容如下WPF代碼如何拖放我使用WPF從一個組合框項目的WPF的文本框
<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 void 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;
}
}
但仍拖放功能不能正常工作。此外,當我嘗試從comboBox拖動一個項目時,它會自動關閉。
你能向我推薦我在這裏失蹤的東西嗎?
FindAncestor與RelativeSource綁定一起使用。我沒有看到任何RelativeSource綁定在這裏完成。 –
此鏈接可以幫助: http://stackoverflow.com/questions/1596797/wpf-drag-drop-on-listbox-item –