Blog
All Blog Posts | Next Post | Previous PostThe unbearable sadness of evolution to WPF/Silverlight
Saturday, March 28, 2009
This week, while doing Silverlight 2.0 development work, we stumbled upon weird behaviour of the KeyDown event with Backspace and Delete key handling. Being familiar with the WM_KEYDOWN message for over 15 years in Windows applications, it always allowed us to fully control the relationship between keys pressed and how a control handles the key. One would think that 15 years later, we'd still be able to do at least the same and preferably more. Now consider following simple scenario: a TextBox control in a WPF application:<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <TextBox Height="23" Margin="42,53,116,0" Name="textBox1" VerticalAlignment="Top" KeyDown="textBox1_KeyDown"/> </Grid> </Window>
with the C# event handler code:
namespace WpfApplication1 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Delete) System.Diagnostics.Debug.WriteLine("DEL"); if (e.Key == Key.Back) System.Diagnostics.Debug.WriteLine("BACK"); } } }
Surprisingly, the KeyDown event is never triggered when the Delete or Backspace keys are pressed (in latest version WPF 3.5). Why isn't this suddenly no longer important to be signaled of pressing the Delete or Backspace key?
Now, move on to WPF light or its little sister Silverlight and test what the behaviour of the same scenario is in a Silverlight application:
<UserControl x:Class="SilverlightApplication1.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> <Grid x:Name="LayoutRoot" Background="White"> <TextBox Height="23" Margin="42,53,116,0" Name="textBox1" VerticalAlignment="Top" KeyDown="textBox1_KeyDown"/> </Grid> </UserControl>
namespace SilverlightApplication1 { public partial class Page : UserControl { public Page() { InitializeComponent(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Delete) System.Diagnostics.Debug.WriteLine("DEL"); if (e.Key == Key.Back) System.Diagnostics.Debug.WriteLine("BACK"); } } }
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Back) System.Diagnostics.Debug.WriteLine("BACK"); if (e.KeyCode == Keys.Delete) System.Diagnostics.Debug.WriteLine("DEL"); } } }
When contacting Microsoft about this issue, the answer was that this is "by design". Sure, inconsistency has always been "by design" at Microsoft.
Bruno Fierens
This blog post has not received any comments yet.
All Blog Posts | Next Post | Previous Post