从WPF中重叠的UserControl获取MouseEvent



我在WPF/C#中的MouseEvents遇到问题
我得到了一些简单的WPF结构:

<Grid Name="ID1" Grid.Column="1" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<customUserControl:CustomUserControl:Name="MainDisplay" UseDefaultContextMenu="False" Grid.Row="0">
<customUserControl:CustomUserControl.ContextMenu>
<ContextMenu>
<MenuItem Header="Thing1" Click="Click1"/>
<MenuItem Header="Thing2" Click="Click2"/>
<MenuItem Header="Thing3" Click="Click3"/>
<MenuItem Header="Thing4" Click="Click4"/>
</ContextMenu>
</customUserControl:CustomUserControl.ContextMenu>
</customUserControl:CustomUserControl>
<Overlay1:OverlayS Name="Overlay_One" Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Transparent"/>
</Grid>

正如您可能看到的,我得到了具有两个重叠UserControls的标准网格。当右键单击CustomUserControl时,我可以访问ContextMenu
Overlay1确实显示了具有透明背景的覆盖。尽管如此,当它显示出来时,我再也无法访问customUserControl的MouseEvents了。但这是必须的

我现在的想法是简单地实现一个切换按钮,在CustomUserControl或Overlay1上的MouseEvents之间切换,同时显示两者。

您可以绕过OverlayS捕获的所有事件到您需要的控件,如:

private void OverlayS_Click(object sender, RoutedEventArgs e)
{                 
if (!e.Handled)
{
// e.Handled = true; //Set to true only when the mouse event must end here
var eventArg = new RoutedEventArgs(e.RoutedEvent);                    
eventArg.Source = sender;
var otherUIControl = CustomUserControl as UIElement;
otherUIControl.RaiseEvent(eventArg);
}  
}

对于其他鼠标事件(预览鼠标按钮、鼠标滚轮等(,您必须创建相应的EventArgs。例如:

private void OverlayS_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (!e.Handled)
{
// e.Handled = true;//Set to true only when the mouse event must end here
var eventArg = new MouseButtonEventArgs(e.MouseDevice,e.Timestamp, e.ChangedButton);
eventArg.RoutedEvent = e.RoutedEvent; 
eventArg.Source = sender;               
var otherUIControl = CustomUserControl as UIElement;
otherUIControl.RaiseEvent(eventArg);
}
}

也许,您不必复制EventArgs并将其传递给其他UiControl。

private void OverlayS_Click(object sender, RoutedEventArgs e)
{                 
if (!e.Handled)
{                    
var otherUIControl = CustomUserControl as UIElement;
otherUIControl.RaiseEvent(e);
}  
}

但是要小心,因为一些鼠标事件可能会到达许多控件,并且它们可能会干扰e.Handled.

最新更新