I am new to WPF and C#. I have code to drag and drop a string from a list box to a textbox, however, I would like the drop to overwrite/replace the text currently in the textbox. Right now the text is inserted into the textbox string at the mouse location where the drop occurs. Here it the WPF and eventhandlers I have so far. Thanks in advance.
<ListBox Name="listbox1" HorizontalAlignment="Left" Height="115" Margin="100,75,0,0"
VerticalAlignment="Top" Width="150" PreviewMouseDown="listbox1_MouseDown">
<ListBoxItem Content="Coffie"></ListBoxItem>
<ListBoxItem Content="Tea"></ListBoxItem>
<ListBoxItem Content="Orange Juice"></ListBoxItem>
<ListBoxItem Content="Milk"></ListBoxItem>
<ListBoxItem Content="Iced Tea"></ListBoxItem>
<ListBoxItem Content="Mango Shake"></ListBoxItem>
</ListBox>
<TextBox Name="textbox1" HorizontalAlignment="Left" Height="23" Margin="351,75,0,0" TextWrapping="Wrap"Text="" VerticalAlignment="Top" Width="120" SpellCheck.IsEnabled="True" Cursor="IBeam"
AcceptsReturn="True" AllowDrop="True" PreviewDragOver="textbox1_PreviewDragOver"
DragEnter="textbox1_DragEnter" Drop="textbox1_Drop"/>
private void listbox1_MouseDown(object sender, MouseButtonEventArgs e)
{
if (listbox1.SelectedItems.Count > 0)
{
ListBoxItem mySelectedItem = listbox1.SelectedItem as ListBoxItem;
if (mySelectedItem != null)
{
DragDrop.DoDragDrop(listbox1, mySelectedItem.Content.ToString(), DragDropEffects.Copy);
}
}
}
private void textbox1_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void textbox1_DragEnter(object sender, DragEventArgs e)
{
textbox1.Clear();
e.Effects = DragDropEffects.Copy;
}
private void textbox1_Drop(object sender, DragEventArgs e)
{
string tstring;
tstring = e.Data.GetData(DataFormats.StringFormat).ToString();
textbox1.Text= tstring;
}
Try to handle the PreviewDrop event instead of Drop
:
private void textbox1_PreviewDrop(object sender, DragEventArgs e)
{
e.Handled = true;
string tstring;
tstring = e.Data.GetData(DataFormats.StringFormat).ToString();
textbox1.Text = tstring;
}