newman
newman

Reputation: 6911

WPF: How to make textblock fire key event?

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.

Upvotes: 5

Views: 2874

Answers (1)

Mark Hall
Mark Hall

Reputation: 54532

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

Upvotes: 6

Related Questions