当 TextBlock 是 UserControl 的一部分时,如何处理 TextBlock.KeyDown 事件? [英] How to handle TextBlock.KeyDown event, when TextBlock is a part of UserControl?

查看:25
本文介绍了当 TextBlock 是 UserControl 的一部分时,如何处理 TextBlock.KeyDown 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的UserControl:

<UserControl x:Class="WPFTreeViewEditing.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock Text="Hello, world!" KeyDown="TextBlock_KeyDown" />
    </Grid>
</UserControl>

我想处理 TextBlock.KeyDown 事件.所以,我在代码隐藏中添加了一个事件处理程序:

I want to handle TextBlock.KeyDown event. So, I've added an event handler to the code-behind:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    private void TextBlock_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Key up!");
    }
}

但它不会触发.怎么了?

but it doesn't fire. What's wrong?

更新.

PreviewKeyDown 也不会触发.

这个UserControl用于HierarchicalDataTemplate然后:

<Window x:Class="WPFTreeViewEditing.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFTreeViewEditing"
        Title="MainWindow" Height="265" Width="419">
    <Grid>
        <TreeView ItemsSource="{Binding}">
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:ViewModel}" ItemsSource="{Binding Items}">
                    <local:UserControl1 />
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</Window>

推荐答案

来自 UIElement.KeyDown:

焦点位于此元素上时按下某个键时发生.

Occurs when a key is pressed while focus is on this element.

您使用的 TextBlock 没有焦点,因此您的 KeyDown 事件将由另一个控件处理.

You're using TextBlock which doesn't have the focus, so your KeyDown event will be handled by another control.

您可以切换到 TextBox 并应用一些样式,使其外观和行为类似于 TextBlock,但您将能够获得焦点并处理事件.

You can switch to TextBox and appy some styles so it'll look and behave like TextBlock, but you'll be able to get the focus and handle the event.

这篇关于当 TextBlock 是 UserControl 的一部分时,如何处理 TextBlock.KeyDown 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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