WPF:如何使textblock fire key事件? [英] WPF: How to make textblock fire key event?

查看:257
本文介绍了WPF:如何使textblock fire key事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TextBlock具有KeyDown和KeyUp事件,但它从未被触发。有没有办法让它发生?

TextBlock has KeyDown and KeyUp event, but it's never fired. Is there a way to make it happen? I just need to detect if any key is pressed.

推荐答案

首先你需要设置 可聚焦 您的TextBlock的属性为True,这将允许您选择项目但不单击以选择它,但如果您处理MouseDown事件您可以手动设置焦点到您的TextBlock。

First of all you will need to set the Focusable Property of your TextBlock to True, This will allow you to Tab to the Item but not Click to select it, but if you handle the MouseDown Event you can manualy set Focus to your TextBlock.

MainWindow.xaml

<Window x:Class="WpfApplication1.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">
    <Grid >
       <TextBlock Name="tb1"  Height="30" Width ="100" IsEnabled="True"  Focusable="True" KeyDown="tb1_KeyDown" MouseDown="tb1_MouseDown">Hello World</TextBlock>
    </Grid>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void tb1_KeyDown(object sender, KeyEventArgs e)
    {
        tb1.Background = Brushes.Blue;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        tb1.Focus();
    }

    private void tb1_MouseDown(object sender, MouseButtonEventArgs e)
    {
        tb1.Focus();
    }
}

这篇关于WPF:如何使textblock fire key事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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