A
A
Alexander2018-04-29 09:12:25
WPF
Alexander, 2018-04-29 09:12:25

How to move the control on the window?

There is a window, in it TextBlock. I need to drag this textblock around the window. I googled and found that this is done using PreviewMouseLeftButtonDown , PreviewMouseLeftButtonUp and MouseMove . But something could not figure out how to do it.
Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-04-29
@AlexNineteen

Let's declare a drag-and-drop variable. If the user is holding the button, then the variable is true. Pressed false.

private void lbl_MouseLeftButtonUp(Object sender, MouseButtonEventArgs e)
{
    canMove = false;
}

private void lbl_MouseLeftButtonDown(Object sender, MouseButtonEventArgs e)
{
    canMove = true;
}

drag and drop
private void Window_MouseMove(Object sender, MouseEventArgs e)
{
    // отменяем перетаскивание, если пользователь не нажал кнопку.
    if (!canMove) return;

    Control control = this.lbl;

    //Берем позиции мыши.
    Double x = e.GetPosition(this).X,
        y = e.GetPosition(this).Y;

    //Устанавливаем значение через margin
    control.Margin = new Thickness(x, y, 0, 0);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question