wpf 回车确定 文本文档 wpf enter key event for textbox

Easy in WPF and code as below:

 

 

http://stackoverflow.com/questions/816334/wpf-a-textbox-that-has-an-event-that-fires-when-the-enter-key-is-pressed

 

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.

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

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):

<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

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

 

 

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.

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

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.

Update

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

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.

 

 

 http://www.netboffin.com/pages/WPFCaptureEnter.php

Capturing the Enter Key in the WPF textbox control

Unlike the visual basic forms textbox control, the WPF textbox control does not have a keypress event. So how do we know when the user has pressed the Enter key while the textbox has focus?

Here's how its done on a standard windows form in vb.net

 
Private Sub TextBox1_KeyPress(ByVal sender As Object,
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If (e.KeyChar = vbCr) Then
            CheckedListBox1.Items.Add(TextBox1.Text)
            TextBox1.Text = ""
            e.Handled = True
        End If
End Sub
 

And here's how we do it with a WPF textbox control.We use the PreviewKeyUp Event and the Key property of e the KeyEventArgs, comparing it to Key.Enter.

 
 
Private Sub TextBox1_PreviewKeyUp(ByVal sender As Object, 
ByVal e As System.Windows.Input.KeyEventArgs) Handles TextBox1.PreviewKeyUp
        If (e.Key = Key.Enter) Then
            ListBox1.Items.Add(TextBox1.Text)
			TextBox1.Text = ""
			e.Handled = True
        End If
End Sub
 
WPF 中,如果你想检测 `TextBox` 是否接收到回车键(Enter 键)的输入,你可以创建一个自定义的文本框行为(Custom Textbox Behavior)。首先,需要创建一个新的 Behavior 类,并在其中添加 KeyDown 事件处理程序,检查按下的是 Enter 键。 以下是一个简单的示例: 1. 创建一个新的行为类,例如 `EnterPressBehavior.cs`: ```csharp public class EnterPressBehavior : Behavior<TextBox> { public static readonly DependencyProperty PressedEnterProperty = DependencyProperty.Register(nameof(PressedEnter), typeof(bool), typeof(EnterPressBehavior), new FrameworkPropertyMetadata(false, OnPressedEnterChanged)); private bool pressedEnter; public bool PressedEnter { get => (bool)GetValue(PressedEnterProperty); set => SetValue(PressedEnterProperty, value); } protected override void OnAttached() { AssociatedObject.KeyDown += OnKeyDown; } protected override void OnDetaching() { AssociatedObject.KeyDown -= OnKeyDown; } private void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Enter) { pressedEnter = true; e.Handled = true; // 阻止默认的回车效果 } } private static void OnPressedEnterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var behavior = (EnterPressBehavior)d; behavior.OnPressedEnterChanged((bool)e.NewValue); } protected virtual void OnPressedEnterChanged(bool pressedEnter) { // 在这里添加你想在按下Enter后执行的代码 } } ``` 在你的 XAML 中应用这个行为: ```xaml <Window xmlns:local="clr-namespace:YourNamespace"> <TextBox Name="textBox" local:EnterPressBehavior.PressedEnter="{Binding Path=PressedEnter, UpdateSourceTrigger=PropertyChanged}" /> </Window> ``` 现在,当你在 `TextBox` 中按 Enter 键时,`PressedEnter` 属性会被设置为 `true`,你可以在这个属性变化的地方添加你需要的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值