WPF: How to make textblock fire key event?

随声附和 提交于 2019-12-10 15:28:57

问题


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.


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/13577235/wpf-how-to-make-textblock-fire-key-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!