WPF Window 分配事件处理程序

WPF Window assigning event handlers

我试图为 WPF window (window B) 分配事件处理程序,就像在 window A 中分配的一样,但是 IDE 说 Cannot access non-static event PreviewKeyDown in static context.也许任何人都知道为什么会这样。我看不出两个 windows.

之间有什么区别

Window答:

<Window x:Class="WindowA"
    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"
    mc:Ignorable="d"
    Title="PreviewDetailWindow"
    Height="512.929"
    Width="809.152"
    MinWidth="240"
    Name="FormWindow"
    WindowStartupLocation="CenterScreen"
    Background="Gray"
    UseLayoutRounding="True"
    SnapsToDevicePixels="True">

Window乙:

<Window x:Class="WindowB"
    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:BasketMap"
    mc:Ignorable="d"
    Title="PlayerWindow"
    Height="300"
    Width="300"
    Background="Gray">

请注意,使用 this.PreviewKeyDown 在两者上效果都很好,但我只是好奇为什么以前的方法在两个 windows.

上效果不佳

WindowB 没有指定名称:

<Window x:Class="WindowB" ... x:Name="PlayerWindow" ...>