Instead of attaching a
PreviewKeyUp
TextBox
TextBox
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);
}
}
<Controls:DefaultTextBoxControl DefaultAction="DefaultTextBoxControl_DefaultAction">
</Controls:DefaultTextBoxControl>
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.