I have a UserControl(CardGUI) that I created for my WPF canvas, and I implemented MouseEvents on the UserControl like the ones below. Thing is when I drag the UserControl from the toolbox onto the canvas, it works just fine, but when I try to add a new control, CardGUI card = new CardGUI(); in my MainForm, I can no longer move the control, and I can’t figure out why this is.
I tried debugging but the events still get triggered when I click on the newly added control, yet I cannot move it.
public void UserControl_MouseLeftButtonDown(object sender,
MouseButtonEventArgs e)
{
if (!inDrag)
{
anchorPoint = e.GetPosition(null);
CaptureMouse();
inDrag = true;
e.Handled = true;
}
}
public void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (inDrag)
{
currentPoint = e.GetPosition(null);
Canvas.SetLeft(this,
Canvas.GetLeft(this) +
(currentPoint.X - anchorPoint.X));
Canvas.SetTop(this,
Canvas.GetTop(this) +
(currentPoint.Y - anchorPoint.Y));
anchorPoint = currentPoint;
e.Handled = true;
}
}
public void UserControl_MouseLeftButtonUp(object sender,
MouseButtonEventArgs e)
{
if (inDrag)
{
ReleaseMouseCapture();
inDrag = false;
e.Handled = true;
}
}
I add the control to my mainform like:
this.deckCard = new CardGUI();
this.deckCard.Margin = new Thickness(xDeckCoord, yDeckCoord, 0, 0);
this.main.Children.Add(this.deckCard);
this.deckCard.IsHitTestVisible = true;
this.deckCard.AllowDrop = true;
I figure it might be that since the method adding the control only gets called once, the location doesnt really update eventhough the event is triggered. I didn’t have that problem if I dragged the control from the ToolBox.
You are adding it to a Canvas, but not setting any position or size
Try adding:
Or use a Grid instead if you want stuff to auto stretch to the available size (which your use of Margin seems to infer)