0

我创建了一个包含 Visuals 集合的 FrameworkElement 子类:

public class GameElement : FrameworkElement
{
    private VisualCollection Visuals { get; }

    public GameElement()
    {
        this.KeyDown += this.OnKeyDown;
        this.MouseDown += this.OnMouseDown;
    }

    private void OnKeyDown(object sender, KeyEventArgs keyEventArgs)
    {
        ... // Does not get fired.
    }

    private void OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        ... // Does get fired.
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        // Draw a transparent background to catch mouse events (otherwise hit testing won't hit anything).
        drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(0, 0, RenderSize.Width, RenderSize.Height));
    }

    protected override int VisualChildrenCount
    {
        get
        {
            return this.Visuals.Count;
        }
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= this.Visuals.Count)
        {
            throw new ArgumentOutOfRangeException();
        }

        return this.Visuals[index];
    }
}

我使用以下代码在 XAML 中显示此元素:

<UserControl
    x:Class="..."
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="Black">

    <Grid Margin="10">
        <local:GameElement x:Name="GameElement" ClipToBounds="True" />
    </Grid>
</UserControl>

我已经尝试了我能想到的一切,但我就是无法触发 KeyDown 事件。我在网上找到的最常用的评论与焦点有关。我已经尝试了 Focusable="True" 和调用 this.Focus() 的所有组合,但没有任何效果。

任何人都知道如何做到这一点?谢谢!

4

2 回答 2

1

为了能够处理按键,您的元素应该被聚焦。如果可以的话,也尝试从控件而不是 FramworkElement 派生它。

public class GameElement : Control
{
    private VisualCollection Visuals { get; }

    public GameElement()
    {
        this.KeyDown += this.OnKeyDown;
        this.MouseDown += this.OnMouseDown;
    }

    private void OnKeyDown(object sender, KeyEventArgs keyEventArgs)
    {
        // Does get fired.
    }

    private void OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        Focus();
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        // Draw a transparent background to catch mouse events (otherwise hit testing won't hit anything).
        drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(0, 0, RenderSize.Width, RenderSize.Height));
    }

    protected override int VisualChildrenCount
    {
        get
        {
            return this.Visuals.Count;
        }
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= this.Visuals.Count)
        {
            throw new ArgumentOutOfRangeException();
        }

        return this.Visuals[index];
    }
}
于 2017-05-10T15:28:28.587 回答
0

我终于通过注册一个也处理已处理事件的类处理程序来让它工作。

EventManager.RegisterClassHandler(typeof(Window), Keyboard.KeyDownEvent, new KeyEventHandler(OnKeyDown), true);
于 2017-05-13T15:32:33.810 回答