c# - WPF:具有在按下 Enter 键时触发的事件的 TextBox

标签 c# wpf xaml custom-controls

我没有将 PreviewKeyUp 事件附加到我的应用程序中的每个 TextBox 并检查按下的键是否为 Enter 键然后执行操作,我决定实现扩展TextBox 的版本,其中包含一个 DefaultAction 事件,该事件在 TextBox 中按下 Enter 键时触发。

我所做的基本上是创建一个新类,该类从 TextBox 扩展到一个公共(public)事件 DefaultAction,如下所示:

public class DefaultTextBoxControl:TextBox
{
    public event EventHandler<EventArgs> DefaultAction = delegate { };

    public DefaultTextBoxControl()
    {
        PreviewKeyUp += DefaultTextBoxControl_PreviewKeyUp;
    }

    void DefaultTextBoxControl_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key != Key.Enter)
        {
            return;
        }
        DefaultAction(this, EventArgs.Empty);
    }
}

然后我从我的应用程序中使用这个自定义文本框,就像这样 (xaml):

<Controls:DefaultTextBoxControl  DefaultAction="DefaultTextBoxControl_DefaultAction">
</Controls:DefaultTextBoxControl>

现在,根据我在学习 WPF 方面的一点经验,我意识到几乎大多数时候都有一种“更酷”(希望更简单)的方式来实现事情

...所以我的问题是,如何改进上述控制? 或者是否有其他方法可以实现上述控制? ...也许只使用声明式代码而不是同时使用声明式 (xaml) 和过程式 (C#)?

最佳答案

看看this blog post几个月前,我将“全局”事件处理程序附加到 TextBox.GotFocus 以选择文本。

基本上你可以在你的 App 类中处理 KeyUp 事件,像这样:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox),
        TextBox.KeyUpEvent,
        new System.Windows.Input.KeyEventHandler(TextBox_KeyUp));

    base.OnStartup(e);
}

private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key != System.Windows.Input.Key.Enter) return;

    // your event handler here
    e.Handled = true;
    MessageBox.Show("Enter pressed");
}

... 现在,您的应用程序中的每个 TextBox 都会在用户输入时调用 TextBox_KeyUp 方法。

更新

正如您在评论中指出的那样,这仅在每个 TextBox 需要执行相同代码时才有用。

要添加像 Enter 按键这样的任意事件,您最好查看 Attached Events .我相信这可以让你得到你想要的。

关于c# - WPF:具有在按下 Enter 键时触发的事件的 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/816334/

相关文章:

wpf - 为什么有些属性需要在样式中定义一个默认值,DataTrigger 才会生效?

C# 从数据库列中获取所有电话号码并用逗号分隔并显示在文本框中

c# - 添加键绑定(bind)列表

c# - 如何在 WPF 中显示按钮被单击(按下)?

wpf使用网格作为itemshost自动将多个项目堆叠在单个 'cell'中

c# - 获取用户在 MSAGL 中点击的 Vertex(Node) Object

c# - 发送完整的数据表还是先使用.Select?

c# - 多项目 Visual Studio 解决方案无法调试一个项目 DLL

c# - 将方法传递给组件

c# - 处理 UWP 应用程序中的 alt 键