Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF: A TextBox that has an event that fires when the Enter Key is pressed
    text
    copied!<p>Instead of attaching a <code>PreviewKeyUp</code> event with each <code>TextBox</code> 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 <code>TextBox</code> that includes a DefaultAction event that fires when an Enter Key is pressed in a <code>TextBox</code>. </p> <p>What I did was basically create a new Class that extends from <code>TextBox</code> with a public event <code>DefaultAction</code>, like such:</p> <pre><code>public class DefaultTextBoxControl:TextBox { public event EventHandler&lt;EventArgs&gt; 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); } } </code></pre> <p>I then use this custom textbox from my app like such (xaml):</p> <pre><code>&lt;Controls:DefaultTextBoxControl DefaultAction="DefaultTextBoxControl_DefaultAction"&gt; &lt;/Controls:DefaultTextBoxControl&gt; </code></pre> <hr> <p>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</p> <p>...so my question is, <strong>How can I improve the above control?</strong> 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#) ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload