WPF窗口下,有时候 既需要点击某些控件响应对应的事件, 也需要点击移动在某个控件上移动整个窗口
效果图
dragwindow.gif
源码
源码
代码
- 需要在容器上绑定三个事件:
PreviewMouseLeftButtonDown、PreviewMouseMove、PreviewMouseLeftButtonUp
- 后台代码如下
private Point _downPoint;
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("hello");
}
private void TestGrid_OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var uiElement = sender as UIElement;
_downPoint = e.GetPosition(uiElement);
}
private void TestGrid_OnPreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var uiElement = sender as UIElement;
var mouseMovePoint = e.GetPosition(uiElement);
if (AppUtils.IsAbleToDrag(mouseMovePoint, _downPoint))
{
this.DragMove();
}
}
}
private void TestGrid_OnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var uiElement = sender as UIElement;
var mouseMovePoint = e.GetPosition(uiElement);
if (AppUtils.IsAbleToDrag(mouseMovePoint, _downPoint))
{
e.Handled = true;
var element = Mouse.Captured;
element?.ReleaseMouseCapture();
}
}
<Grid Background="Black"
PreviewMouseLeftButtonDown="TestGrid_OnPreviewMouseLeftButtonDown"
PreviewMouseMove="TestGrid_OnPreviewMouseMove"
PreviewMouseLeftButtonUp="TestGrid_OnPreviewMouseLeftButtonUp">
<StackPanel Orientation="Vertical">
<Button Content="Hello"
Background="Aqua"
Click="ButtonBase_OnClick">
</Button>
<CheckBox Content="Checkbox1"
Foreground="Red"
Background="Red">
</CheckBox>
<RadioButton Content="RadioButton1"
Background="Aqua"
Foreground="Red">
</RadioButton>
</StackPanel>
</Grid>
进阶
网友评论