The work on CodePlant framework was so interesting that I almost forgot writing posts to my blog. Since release of Silverlight 2.0, I have spend a lot of time porting WPF features to the Silverlight based world. I will try to share some simple tips and tricks for Silverlight development.
One of the customer requests was to support upper-case only text boxes in Silverlight. This feature is in WPF fully supported through the TextBox.CharacterCasing property (http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.charactercasing.aspx). But no such property exists in Silverlight TextBox.
Well, we have to handle the KeyDown event for the TextBox ourselves. The KeyEventArgs argument for this event has a property PlatformKeyCode. The problem and maybe the advantage in this case is that PlatformKeyCode does not take into consideration any modifiers (e.g. 'a' and 'A' are both 65).
So you can get upper-case character just by converting this value to .Net char and insert the char in the Text property of the TextBox.
char
upper = (char)e.PlatformKeyCode;
In the KeyDown event just avoid the keystrokes , that you do not want to handle, you can keep in the list
List<Key> skipKeys = new List<Key>(new Key[] { Key.F1, Key.F2, Key.F3, Key.F4, Key.F5,......});
and check in the event the pressed Key against this list.
The last problem is that there is no CaretPosition in the Silverlight TextBlock, but the SelectionStart property has almost the same behaviour and for this case is suitable.
So the full code is
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
List skipKeys = new List(new Key[] { Key.F1, Key.F2, Key.F3, Key.F4, Key.F5, Key.F6, Key.F7, Key.F8, Key.F9, Key.F10, Key.F11, Key.F12, Key.Tab });
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
TextBox tb=(TextBox) sender;
if (skipKeys.Contains(e.Key)) return;
//do not hanlde ModifierKeys
if (Keyboard.Modifiers == ModifierKeys.Shift) return;
if (Keyboard.Modifiers == ModifierKeys.Control) return;
//clear the selection
if (tb.SelectedText.Length > 0)
tb.SelectedText = "";
string s=new string(new char[] {(char)e.PlatformKeyCode});
int i=tb.SelectionStart;
tb.Text= tb.Text.Insert(i,s);
tb.Select(i+1, 0);
e.Handled = true;
}
}
And in the XAML part you have
<TextBox KeyDown="TextBox_KeyDown"/>
Enjoy.