Prev | Current Page 329 | Next

Matthew MacDonald

"Pro WPF with VB 2008: Windows Presentation Foundation with .NET 3.5"

That means depending on
how you press the number 9, you might get a value of Key.D9 or Key.NumPad9. Checking for
all the allowed key values is tedious, to say the least.
One option is to use the KeyConverter to convert the Key value into a more useful string.
For example, using KeyConverter.ConvertToString() on both Key.D9 and Key.NumPad9 returns
???9??? as a string. If you just use the Key.ToString() conversion, you??™ll get the much less useful
enumeration name (either ???D9??? or ???NumPad9???):
Dim converter As New KeyConverter()
Dim key As String = converter.ConvertToString(e.Key)
CHAPTER 6 n DEPENDENCY PROPERTIES AND ROUTED EVENTS 172
However, even using the KeyConverter is a bit awkward because you??™ll end up with longer
bits of text (such as ???Backspace???) for keystrokes that don??™t result in text input.
The best compromise is to handle both PreviewTextInput (which takes care of most of the
validation) and use PreviewKeyDown for keystrokes that don??™t raise PreviewTextInput in the
text box (such as the space key). Here??™s a simple solution that does it:
Private Sub pnl_PreviewTextInput(ByVal sender As Object, _
ByVal e As TextCompositionEventArgs)
Dim val As Short
If Not Int16.TryParse(e.Text, val) Then
e.Handled = True
End If
End Sub
Private Sub pnl_PreviewKeyDown(ByVal sender As Object, _
ByVal e As KeyEventArgs)
If e.


Pages:
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341