C# WPF:使鼠标在背面输入/离开工作,同时单击正面的工作

C# WPF:使鼠标在背面输入/离开工作,同时单击正面的工作,c#,wpf,routed-events,C#,Wpf,Routed Events,下面的代码是我的难题的完整示例。我需要鼠标进入/离开事件在后面的对等机上工作,而在前面的对等机上仍然有鼠标事件工作。到目前为止,我只能得到其中一个。我通过删除前网格上的背景来让背景事件工作,然后我的单击事件不工作。我如何才能使此中的所有事件都起作用?我真的不想改变逻辑/视觉结构,因为我的实际应用程序比这个示例复杂得多 using System; using System.Windows; using System.Windows.Controls; using System.Windows.In

下面的代码是我的难题的完整示例。我需要鼠标进入/离开事件在后面的对等机上工作,而在前面的对等机上仍然有鼠标事件工作。到目前为止,我只能得到其中一个。我通过删除前网格上的背景来让背景事件工作,然后我的单击事件不工作。我如何才能使此中的所有事件都起作用?我真的不想改变逻辑/视觉结构,因为我的实际应用程序比这个示例复杂得多

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace DemoBadEnterEvent
{
    class Program
    {
        [STAThread]
        public static void Main()
        {
            var frontGrid = new Grid
            {
                Background = Brushes.Transparent // remove this for enter/leave to work
            };

            var backGrid = new Grid();
            var backEllipse = new Ellipse
            {
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                Width = 200,
                Height = 200,
                Fill = Brushes.LightSteelBlue,
                StrokeThickness = 10,
                Stroke = Brushes.Transparent,
                Cursor = Cursors.Arrow
            };

            var window = new Window { Width = 300, Height = 300, Cursor = Cursors.Cross };
            var app = new Application();
            backGrid.Children.Add(backEllipse);
            backGrid.Children.Add(frontGrid);
            window.Content = backGrid;

            backEllipse.MouseEnter += (sender, args) => backEllipse.Fill = Brushes.MediumVioletRed;
            backEllipse.MouseLeave += (sender, args) => backEllipse.Fill = Brushes.LightSteelBlue;
            frontGrid.MouseLeftButtonDown += (sender, args) => backEllipse.Stroke = Brushes.Salmon;
            frontGrid.MouseLeftButtonUp += (sender, args) => backEllipse.Stroke = Brushes.Transparent;

            app.Run(window);
        }
    }
}

如果不更改布局,您将无法在backEllipse上获取鼠标事件。您可以做的一件事是在前栅格上捕捉鼠标移动,并在后栅格上执行命中测试:

frontGrid.MouseMove += (sender, args) => backEllipse.Fill = 
    (VisualTreeHelper.HitTest(backEllipse, args.GetPosition(backEllipse)) == null)
    ? Brushes.LightSteelBlue
    : Brushes.MediumVioletRed;

注意:我尝试绑定到IsMouseOver属性,但它在MouseEnter上没有任何内容。那么MouseEnter行为是否与每个MouseMove上的命中测试相同?还是本地的鼠标会比这更有效?