我在WPF中有一个UserControl。我也有一个无边框窗口。要移动它 - 我使用DragMove。 但是 - 要在用户控件中获取单击事件 - 我使用PreviewMouseLeftButtonUp事件并在UserControl_MouseEnter上捕获鼠标。 问题是 - 如果我点击控件,然后移动窗口 - 当点击靠近控件而不是它时,也可以触发事件。
这是我的代码:
UserControl1.xaml:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" MouseEnter="UserControl_MouseEnter" MouseLeave="UserControl_MouseLeave">
<Grid>
</Grid>
</UserControl>
UserControl1.xaml.cs:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void UserControl_MouseEnter(object sender, MouseEventArgs e)
{
CaptureMouse();
}
private void UserControl_MouseLeave(object sender, MouseEventArgs e)
{
ReleaseMouseCapture();
}
}
MainWindow.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication1" WindowStyle="None" MouseLeftButtonDown="Window_MouseLeftButtonDown">
<Grid>
<my:UserControl1 Margin="39,29,380,199" Background="Red" PreviewMouseLeftButtonUp="UserControl1_PreviewMouseLeftButtonUp">
</my:UserControl1>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
private void UserControl1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Hello World");
}
}
如果您运行此应用程序 - 您将看到如果您单击控件,然后拖动窗口,然后单击控件附近(侧面可能会有所不同) - 它将触发PreviewMouseLeftButtonUp事件,即使您没有点击控件本身。
任何想法如何解决这个问题? 谢谢!
答案 0 :(得分:0)
我四处询问,发现要解决问题,我需要更改User控件的事件: 而不是MouseLeave-我使用MouseMove。
private void UserControl_MouseEnter(object sender, MouseEventArgs e)
{
if (this.IsEnabled)
CaptureMouse();
}
private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
Point mouseposition = e.GetPosition(this);
if (mouseposition.X < 0 || mouseposition.Y < 0 || mouseposition.X > this.ActualWidth || mouseposition.Y > this.ActualHeight)
ReleaseMouseCapture();
}