Draggable control in WPF?

别来无恙 提交于 2019-12-10 10:42:29

问题


I'm kind of new to WPF although I have some experience in Forms, and I decided to finally try to figure out how to use WPF. So When I got to draggable controls, this is the code I came up with (I attempted to change it to work with WPF but the control just twitches everywhere):

private void rectangle1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed) {
        double x = this.Left + (double)e.GetPosition(this).X - (double)rectangle1.Margin.Left;
        double y = this.Top + (double)e.GetPosition(this).Y - (double)rectangle1.Margin.Top;
        rectangle1.Margin = new Thickness(x, y, rectangle1.Margin.Right, rectangle1.Margin.Bottom);
    }
}

回答1:


You want to use adorners to achieve dragging, resizing, rotating, etc.




回答2:


If you want to do it by hands use following algorithm:

  1. On MouseDown event: Save Mouse position, TopLeft position of control, and delta(offset) of these coordinates, and set some boolean field flag eg. IsDragStartted to true.
  2. On MouseMove check that drag started and use Mouse position and offset to calculate the new value of TopLeft position of control

  3. On MouseUp event set IsDragStartted to false




回答3:


here is a pretty good article on the matter on MSDN. also, a quick search on Google revealse a veritable cornucopia of choices for you DnD dining pleasure.



来源:https://stackoverflow.com/questions/10022605/draggable-control-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!