WPF:一个TextBox,它有一个按下Enter键时触发的事件

时间:2022-09-20 14:42:10

Instead of attaching a PreviewKeyUp event with each TextBox in 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 TextBox that includes a DefaultAction event that fires when an Enter Key is pressed in a TextBox.

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

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

我所做的基本上是创建一个新的类,它使用公共事件DefaultAction从TextBox扩展,如下所示:

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#)?

5 个解决方案

#1


27  

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

几个月前看一下这篇博客文章,我将一个'全局'事件处理程序附加到TextBox.GotFocus来选择文本。

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

基本上你可以在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");
}

... and now every TextBox in your application will call the TextBox_KeyUp method as users type into them.

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

Update

更新

As you've pointed out in your comment, this is only useful if every TextBox needs 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键一样的任意事件,您可能最好不要查看附加事件。我相信这可以让你得到你想要的。

#2


13  

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

由于问了这个问题,现在TextBoxes和其他控件上有一个InputBindings属性。有了这个,可以使用纯XAML解决方案,而不是使用自定义控件。为Return和Enter分配KeyBinding以指向命令可以执行此操作。

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 Enter does not always work, and Return may be used on some systems.

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

#3


0  

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

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

#4


0  

add event in xaml to the specific textbox or object:

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

KeyDown="txtBarcode_KeyDown"

的KeyDown = “txtBarcode_KeyDown”

#5


0  

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 MSDN Doc

有关更多信息,请阅读MSDN Doc

#1


27  

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

几个月前看一下这篇博客文章,我将一个'全局'事件处理程序附加到TextBox.GotFocus来选择文本。

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

基本上你可以在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");
}

... and now every TextBox in your application will call the TextBox_KeyUp method as users type into them.

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

Update

更新

As you've pointed out in your comment, this is only useful if every TextBox needs 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键一样的任意事件,您可能最好不要查看附加事件。我相信这可以让你得到你想要的。

#2


13  

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

由于问了这个问题,现在TextBoxes和其他控件上有一个InputBindings属性。有了这个,可以使用纯XAML解决方案,而不是使用自定义控件。为Return和Enter分配KeyBinding以指向命令可以执行此操作。

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 Enter does not always work, and Return may be used on some systems.

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

#3


0  

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

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

#4


0  

add event in xaml to the specific textbox or object:

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

KeyDown="txtBarcode_KeyDown"

的KeyDown = “txtBarcode_KeyDown”

#5


0  

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 MSDN Doc

有关更多信息,请阅读MSDN Doc