TextBlock 具有 KeyDown 和 KeyUp 事件,但它从未被触发。有没有办法实现它? 我只需要检测是否按下了任何键。
首先
,您需要将文本块的Focusable
属性设置为 True,这将允许您按 Tab 键转到该项,但不能单击以选择它,但是如果您处理鼠标按下事件,您可以手动将焦点设置为您的文本块。
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();
}
}