Make WPF window draggable, no matter what element is clicked

前端 未结 9 1039
灰色年华
灰色年华 2020-12-04 07:47

My question is 2 fold, and I am hoping there are easier solutions to both provided by WPF rather than the standard solutions from WinForms (which Christophe

9条回答
  •  余生分开走
    2020-12-04 08:29

    As already mentioned by @fjch1997 it's convenient to implement a behavior. Here it is, the core logic is the same as in the @loi.efy's answer:

    public class DragMoveBehavior : Behavior
    {
        protected override void OnAttached()
        {
            AssociatedObject.MouseMove += AssociatedObject_MouseMove;
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
        }
    
        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && sender is Window window)
            {
                // In maximum window state case, window will return normal state and
                // continue moving follow cursor
                if (window.WindowState == WindowState.Maximized)
                {
                    window.WindowState = WindowState.Normal;
    
                    // 3 or any where you want to set window location after
                    // return from maximum state
                    Application.Current.MainWindow.Top = 3;
                }
    
                window.DragMove();
            }
        }
    }
    

    Usage:

    
        
            
        
        ...
    
    

提交回复
热议问题