KeyDown事件未从网格引发 [英] KeyDown event not raising from a grid

查看:86
本文介绍了KeyDown事件未从网格引发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有一个带有网格的示例窗口.我需要在按下键时捕获事件.但是,当我单击网格区域然后按键时,它没有上升.仅在重点关注文本框"时才有效.我知道如果我从Window捕获它,它将起作用.但是我有其他应用程序,用户控件很少,我需要从不同的控件中捕获它.我尝试为Window设置Focusable.false,为Grid设置true,但这无济于事. 有解决方案吗?

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>

推荐答案

对,这很奇怪.显然,这是一个焦点问题,即使我单击网格,我仍然不明白为什么网格无法获得焦点.

Right this is weird. This is clearly a focus problem, still I can not understand why the grid do not take Focus, even when we click on it.

尽管有一种解决方法:为网格的已加载事件创建一个处理程序:

Though there is a workaround: create an handler for the loaded event of the grid:

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

然后将焦点集中在您的代码后面:

And then force focus in your code behind:

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

您的keydown事件将在此之后起作用. 希望对您有所帮助.

Your keydown event will work after that. Hope it helps.

这篇关于KeyDown事件未从网格引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆