I seem to be having a peculiar problem with drag and dropping button content into a textbox. If I run my program in debug, it only appends the content of the button to the textbox once, but if I run it without debugging it appends twice.
Here is the XAML:
<TextBox x:Name="tbxExpression" Grid.Column="0" Grid.ColumnSpan="2" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Height="50" Margin="5,5,5,47.5" TextAlignment="Right" FontSize="24" Background="#F4F9FD" AllowDrop="True" DragEnter="tbxExpression_Dragging" Drop="tbxExpression_Drop" PreviewDragEnter="tbxExpression_Dragging" PreviewDragOver="tbxExpression_Dragging" DragOver="tbxExpression_Dragging"></TextBox>
<Button x:Name="btnNumOne" Grid.Row="2" Grid.Column="0" Content="1" Margin="5" FontSize="14" Background="#EBF1F6" PreviewMouseLeftButtonDown="button_PreviewMouseLeftButtonDown" MouseMove="button_PreviewMouseMove" PreviewMouseMove="button_PreviewMouseMove"></Button>
And the CS:
private void tbxExpression_Dragging(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
e.Effects = DragDropEffects.Copy;
else
e.Effects = DragDropEffects.None;
e.Handled = true;
}
private void tbxExpression_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
// Get the dragged data and place it in textbox.
string content = e.Data.GetData(typeof(string)).ToString();
TextBox tbx = (TextBox)sender;
tbx.AppendText(content);
}
}
// Button Events for Dragging.
private void button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null); // Absolute position.
}
private void button_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (IsDragging(startPoint, e))
{
// Get the dragged button
Button btn = (Button)sender;
if (btn != null)
{
// Initialize the drag and drop.
DataObject dragData = new DataObject(typeof(string), btn.Content.ToString());
DragDrop.DoDragDrop(btn, dragData, DragDropEffects.Copy);
e.Handled = true;
}
}
}
// Helper
private static bool IsDragging(Point dragStart, MouseEventArgs e)
{
Vector diff = e.GetPosition(null) - dragStart;
return e.LeftButton == MouseButtonState.Pressed && (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance);
}
If I drag the content of btnNumOne over to the textbox and drop it, I get "11" in the textbox but if I debug and do the same operation, I only get "1" like it should be. Does anyone know why I could be getting this duplication of text?