我无法在自定义FrameworkElement上解雇MouseMove事件,该事件将用作图形的宿主。

下一个示例代码显示了这种情况:

namespace WpfAppTest
{
  public class VisualPresenter : FrameworkElement
  {
    private readonly List<Visual> VisualChildren = new List<Visual>();
    public Size ViewSize = new Size(500, 300);

    public VisualPresenter()
    {
        var DrwVis = new DrawingVisual();
        using (var Context = DrwVis.RenderOpen())
            Context.DrawDrawing(
                  new GeometryDrawing(Brushes.LightSkyBlue, null,
                                      new RectangleGeometry(new Rect(ViewSize))));
        this.VisualChildren.Add(DrwVis);
    }

    protected override int VisualChildrenCount { get { return VisualChildren.Count; } }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= VisualChildren.Count) throw new ArgumentOutOfRangeException();
        return VisualChildren[index];
    }

    protected override Size MeasureOverride(Size AvailableSize)
    { return this.ViewSize; }

    protected override Size ArrangeOverride(Size FinalSize)
    { return base.ArrangeOverride(FinalSize); }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        // Why this is not fired when the mouse is over???
        Application.Current.MainWindow.Title = "Moving at: " + e.GetPosition(null);
    }
  }
}


在主窗口xaml中插入此“自定义控件”(如果该概念适用于此处),就可以轻松对其进行测试...

<Window x:Class="WpfAppTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfAppTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="700" Width="600">
    <Grid>
        <local:VisualPresenter />
    </Grid>
</Window>


那么,缺少了什么呢?

更新1:
我发现捕获鼠标时会触发mousemove事件,例如在VisualPresenter构造函数中添加下一行时:

this.Loaded += (s, e) => CaptureMouse();


更新2:
或者,当使用VisualCollection而不是List来注册子项时,也会触发mousemove事件。但是我宁愿使用列表来存储更多内容,而不仅仅是视觉内容(即识别那些暴露的视觉内容的关键)。

最佳答案

没有背景被认为是空心的并且不能吸收鼠标事件。默认情况下,Framework Elements没有视觉效果。因此,命中测试将基于在OnRender方法中绘制的内容进行。可以通过在渲染上绘制一个空白的透明矩形来启用点击测试。

    protected override void OnRender(DrawingContext drawingContext)
    {
        drawingContext.DrawRectangle(Brushes.Transparent, new Pen(Brushes.Transparent, 1), new Rect(0, 0, this.ActualWidth, this.ActualHeight));
        base.OnRender(drawingContext);
    }

关于c# - 为什么未在自定义FrameworkElement上触发MouseMove?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27153558/

10-13 05:35