我正在制作一个Windows风格=无的WPF应用程序,我设法在我的窗口中创建和工作退出按钮,但我不知道如何在按下鼠标左键时拖动它。 我在.cs文件中创建了鼠标左按钮事件,如下所示:
private void see(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
然后我在.xaml文件中添加了边框来拖动窗口,如下所示:
<Grid>
<Border BorderThickness="2" BorderBrush="Black" Height="120" Width="100" MouseLeftButtonDown="see" />
</Grid>
现在我不明白这里有什么问题?如果有人帮助我,我会非常感激吗?
答案 0 :(得分:1)
对此窗口使用类似的模式:
public class DragableWindowNoStyle : Window
{
public DragableWindowNoStyle()
{
WindowStyle = WindowStyle.None;
Grid grid = new Grid() { };
_moveBorder = new Border()
{
BorderThickness = new Thickness(2),
BorderBrush = Brushes.Red,
Background = Brushes.Black,
Width = 50,
Height = 20,
HorizontalAlignment= System.Windows.HorizontalAlignment.Center,
VerticalAlignment = System.Windows.VerticalAlignment.Top,
};
grid.Children.Add(_moveBorder);
this.Content = grid;
_moveBorder.PreviewMouseLeftButtonDown += _moveBorder_PreviewMouseLeftButtonDown;
}
Point _startPoint;
bool _isDragging = false;
Border _moveBorder;
private void _moveBorder_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (Mouse.Capture(this))
{
_isDragging = true;
_startPoint = PointToScreen(Mouse.GetPosition(this));
}
}
protected override void OnPreviewMouseMove(MouseEventArgs e)
{
if (_isDragging)
{
Point newPoint = PointToScreen(Mouse.GetPosition(this));
int diffX = (int)(newPoint.X - _startPoint.X);
int diffY = (int)(newPoint.Y - _startPoint.Y);
if (Math.Abs(diffX) > 1 || Math.Abs(diffY) > 1)
{
Left += diffX;
Top += diffY;
InvalidateVisual();
_startPoint = newPoint;
}
}
}
protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (_isDragging)
{
_isDragging = false;
Mouse.Capture(null);
}
}
}
答案 1 :(得分:0)
有一个示例如何创建一个自定义窗口,其中包括从头开始调整大小,拖动,最小化,恢复和关闭功能:
如何在WPF中创建自定义窗口: https://blog.magnusmontin.net/2013/03/16/how-to-create-a-custom-window-in-wpf/
您还可以使用WindowChrome
类https://msdn.microsoft.com/en-us/library/system.windows.shell.windowchrome(v=vs.110).aspx自定义窗口,同时保留其标准功能。然后您不必自己实现调整大小和拖动功能。