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