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 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):
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.
WPF实现TextBox回车事件的方法探讨
博客围绕WPF中实现TextBox回车事件展开。作者先创建扩展类实现该功能,后询问有无更好方式。解决方案提出在App类处理KeyUp事件,使所有TextBox响应回车。还提到若需添加任意事件,可考虑附加事件。
5612

被折叠的 条评论
为什么被折叠?



