10

Here I have sample window with a grid. I need to capture event when key is pressed. But it is not raising when I click grid area and then press key. It will work only if Textbox is focused. I know it will work if I capture it from Window. But I have other application with few usercontrols and I need to capture it from distinct ones. I tried to set Focusable.false for Window and true for Grid but it not helps. Any solutions?

<Window x:Class="Beta.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Closed="Window_Closed_1" Focusable="False">

    <Grid KeyDown="Grid_KeyDown_1" Focusable="True">
    <TextBox x:Name="tbCount" HorizontalAlignment="Left" Height="35" Margin="310,49,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="83"/>

  </Grid>

4

3 に答える 3

8

まさにこれは奇妙です。これは明らかにフォーカスの問題ですが、それでもグリッドをクリックしてもグリッドがフォーカスを取得しない理由がわかりません。

回避策はありますが、グリッドのロードされたイベントのハンドラーを作成します。

<Grid x:Name="theGrid" KeyDown="Grid_KeyDown_1" Focusable="True" Loaded="TheGrid_OnLoaded">

そして、背後にあるコードにフォーカスを強制します。

    private void TheGrid_OnLoaded(object sender, RoutedEventArgs e)
    {
        theGrid.Focus();
    }

その後、キーダウンイベントが機能します。それが役に立てば幸い。

于 2013-03-06T07:47:23.557 に答える
7

ユニバーサルWindowsプラットフォーム(UWP)アプリでも同じ問題が発生しました。イベントをXAMLのグリッドに添付しましたが、テキストボックスにフォーカスがある場合にのみ機能します。私はMSDNで答えを見つけました(回避策だけではありません):https ://social.msdn.microsoft.com/Forums/en-US/56272bc6-6085-426a-8939-f48d71ab12ca/page-keydown-event-not-firing ?forum = winappswithcsharp

要約すると、その投稿によると、TextBoxへのフォーカスが失われると、グリッドが取得しないようにイベントが上位に渡されるため、イベントは発生しません。Window.Current.CoreWindow.KeyDown代わりに使用する必要があります。次のように、ページが読み込まれたイベントにイベントハンドラーを追加しました。

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    Window.Current.CoreWindow.KeyDown += coreWindow_KeyDown;
    Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;
}

これは私にとって期待どおりに機能します。

于 2015-11-16T12:32:20.180 に答える
3

Focusableプロパティをtrueに設定するまで(デフォルトはFalseでした)、Focusメソッドも使用してみましたが無駄になりました。

于 2017-08-13T05:48:16.033 に答える