C# WPF:一个文本框,当按下 Enter 键时会触发一个事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/816334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:19:44  来源:igfitidea点击:

WPF: A TextBox that has an event that fires when the Enter Key is pressed

c#wpfxamlcustom-controls

提问by Andreas Grech

Instead of attaching a PreviewKeyUpevent with each TextBoxin my app and checking if the pressed key was an Enter key and then do an action, I decided to implement extended version of a TextBoxthat includes a DefaultAction event that fires when an Enter Key is pressed in a TextBox.

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

What I did was basically create a new Class that extends from TextBoxwith a public event DefaultAction, like such:

我所做的基本上是创建一个从TextBox公共事件扩展的新类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);
    }
}

I then use this custom textbox from my app like such (xaml):

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

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


Now in my little experience I've had in learning WPF I've realized that almost most of the time there is a "cooler" (and hopefully easier) way to implement things

现在,在我学习 WPF 的一点经验中,我意识到几乎大部分时间都有一种“更酷”(希望更简单)的方法来实现事物

...so my question is, How can I improve the above control?Or maybe is there another way I can do the above control? ...maybe using only declarative code instead of both declarative (xaml) and procedural (C#) ?

...所以我的问题是,如何改进上述控制?或者也许有另一种方法可以进行上述控制?...也许只使用声明性代码而不是声明性 (xaml) 和程序性 (C#) ?

采纳答案by Matt Hamilton

Have a look at this blog postfrom a few months back where I attach a 'global' event handler to TextBox.GotFocusto select the text.

看看几个月前的这篇博客文章,我在其中附加了一个“全局”事件处理程序TextBox.GotFocus来选择文本。

Essentially you can handle the KeyUpevent in your App class, like this:

本质上,您可以KeyUp在 App 类中处理事件,如下所示:

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

... and now every TextBoxin your application will call the TextBox_KeyUpmethod as users type into them.

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

Update

更新

As you've pointed out in your comment, this is only useful if every TextBoxneeds to execute the same code.

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

To add an arbitrary event like an Enter keypress, you might be better off looking into Attached Events. I believe this can get you what you want.

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

回答by Cyral

Since this question was asked, there is now an InputBindingsproperty on TextBoxes and other controls. With this, a purely XAML solution can be used, rather than using custom controls. Assigning KeyBindings for Returnand Enterto point to a command can do this.

由于提出了这个问题,因此现在InputBindingsTextBoxes 和其他控件上有一个属性。有了这个,就可以使用纯粹的 XAML 解决方案,而不是使用自定义控件。分配KeyBindings forReturnEnterto 指向一个命令可以做到这一点。

Example:

例子:

<TextBox Text="Test">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="Return" />
        <KeyBinding Command="{Binding SomeCommand}" Key="Enter" />
    </TextBox.InputBindings>
</TextBox>

Some have mentioned that Enterdoes not always work, and Returnmay be used on some systems.

有人提到这Enter并不总是有效,并且Return可能在某些系统上使用。

回答by joseph

    private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
    {
        string etr = e.Key.ToString();

        if (etr == "Return")
        {
            MessageBox.Show("You Press Enter");
        }
    }

回答by joseph

add event in xamlto the specific textbox or object:

将事件添加xaml到特定的文本框或对象:

KeyDown="txtBarcode_KeyDown"

KeyDown="txtBarcode_KeyDown"

回答by Ali Asad

When the user presses the Enter key in the TextBox, the input in the text box appears in another area of the user interface (UI).

当用户在 TextBox 中按下 Enter 键时,文本框中的输入会出现在用户界面 (UI) 的另一个区域中。

The following XAML creates the user interface, which consists of a StackPanel, a TextBlock, and a TextBox.

以下 XAML 创建用户界面,它由 StackPanel、TextBlock 和 TextBox 组成。

<StackPanel>
  <TextBlock Width="300" Height="20">
    Type some text into the TextBox and press the Enter key.
  </TextBlock>
  <TextBox Width="300" Height="30" Name="textBox1"
           KeyDown="OnKeyDownHandler"/>
  <TextBlock Width="300" Height="100" Name="textBlock1"/>
</StackPanel>

The following code behind creates the KeyDown event handler. If the key that is pressed is the Enter key, a message is displayed in the TextBlock.

下面的代码创建了 KeyDown 事件处理程序。如果按下的键是 Enter 键,则 TextBlock 中会显示一条消息。

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        textBlock1.Text = "You Entered: " + textBox1.Text;
    }
}

For more info read MSDNDoc

有关更多信息,请阅读MSDN文档