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

And*_*ech 19 c# wpf xaml custom-controls

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

我所做的基本上是创建一个新的类,从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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<Controls:DefaultTextBoxControl  DefaultAction="DefaultTextBoxControl_DefaultAction">
</Controls:DefaultTextBoxControl>
Run Code Online (Sandbox Code Playgroud)

现在,在我学习WPF的过程中,我已经意识到几乎大多数时候都有一种"更酷"(希望更容易)的方式来实现

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

Mat*_*ton 35

几个月前看看这篇博文,我附上一个"全局"事件处理程序TextBox.GotFocus来选择文本.

基本上你可以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");
}
Run Code Online (Sandbox Code Playgroud)

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

更新

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

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


Cyr*_*ral 27

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

例:

<TextBox Text="Test">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="Return" />
        <KeyBinding Command="{Binding SomeCommand}" Key="Enter" />
    </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

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


Ali*_*sad 5

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

以下 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>
Run Code Online (Sandbox Code Playgroud)

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

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

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