我的 WPF 应用程序有一个UserControl
看起来和行为都应该像弹出窗口的窗口,但它不是窗口。控件不属于Window
该类的原因是因为它包含第三方虚拟屏幕键盘,并且该控件必须与TextBox
当您单击其按钮时将输入字符发送到的控件位于同一窗口中. 如果键盘控件不在同一个窗口中,它甚至看不到TextBox
控件。
我遇到的问题是拖动对话框时性能非常糟糕。鼠标离开拖动区域并停止跟随鼠标的速度足够慢。我需要一个更好的方法。
这是控件的 xaml 的摘录:
<Grid Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Background="{DynamicResource PopupBackground}"
BorderBrush="{DynamicResource PopupBorder}"
BorderThickness="5,5,5,0"
MouseLeftButtonDown="Grid_MouseLeftButtonDown"
MouseLeftButtonUp="Grid_MouseLeftButtonUp"
MouseMove="Grid_MouseMove">
. . .
</Border>
</Grid>
这是鼠标事件处理程序:
private void Grid_MouseLeftButtonDown( object sender, MouseButtonEventArgs e ) {
Canvas canvas = Parent as Canvas;
if ( canvas == null ) {
throw new InvalidCastException( "The parent of a KeyboardPopup control must be a Canvas." );
}
DraggingControl = true;
CurrentMousePosition = e.GetPosition( canvas );
e.Handled = true;
}
private void Grid_MouseLeftButtonUp( object sender, MouseButtonEventArgs e ) {
Canvas canvas = Parent as Canvas;
if ( canvas == null ) {
throw new InvalidCastException( "The parent of a KeyboardPopup control must be a Canvas." );
}
if ( DraggingControl ) {
Point mousePosition = e.GetPosition( canvas );
// Correct the mouse coordinates in case they go off the edges of the control
if ( mousePosition.X < 0.0 ) mousePosition.X = 0.0; else if ( mousePosition.X > canvas.ActualWidth ) mousePosition.X = canvas.ActualWidth;
if ( mousePosition.Y < 0.0 ) mousePosition.Y = 0.0; else if ( mousePosition.Y > canvas.ActualHeight ) mousePosition.Y = canvas.ActualHeight;
// Compute the new Left & Top coordinates of the control
Canvas.SetLeft( this, Left += mousePosition.X - CurrentMousePosition.X );
Canvas.SetTop( this, Top += mousePosition.Y - CurrentMousePosition.Y );
}
e.Handled = true;
}
private void Grid_MouseMove( object sender, MouseEventArgs e ) {
Canvas canvas = Parent as Canvas;
if ( canvas == null ) {
// It is not. Throw an exception
throw new InvalidCastException( "The parent of a KeyboardPopup control must be a Canvas." );
}
if ( DraggingControl && e.LeftButton == MouseButtonState.Pressed ) {
Point mousePosition = e.GetPosition( canvas );
// Correct the mouse coordinates in case they go off the edges of the control
if ( mousePosition.X < 0.0 ) mousePosition.X = 0.0; else if ( mousePosition.X > canvas.ActualWidth ) mousePosition.X = canvas.ActualWidth;
if ( mousePosition.Y < 0.0 ) mousePosition.Y = 0.0; else if ( mousePosition.Y > canvas.ActualHeight ) mousePosition.Y = canvas.ActualHeight;
// Compute the new Left & Top coordinates of the control
Canvas.SetLeft( this, Left += mousePosition.X - CurrentMousePosition.X );
Canvas.SetTop ( this, Top += mousePosition.Y - CurrentMousePosition.Y );
CurrentMousePosition = mousePosition;
}
e.Handled = true;
}
请注意,该控件必须放在Canvas
使用它的窗口中的 a 内。
我不能使用DragMove
它,因为它是该类的方法,Window
并且该类从UserControl
. 如何提高此控件的拖动性能?我必须求助于 Win32 API 吗?