problem with converting simple code from Winform to silverlight app
I have this code for window form application and I have been attempting to convert it to a Silverlight application but it does not work!. There is a Textbox and I attached KeyDown event handler to it. when the user press the arrow key ( left or right) while the focus on the textbox, it will write . or -. When it is window form i used e.KeyCode and Keys.Right and its works great but when it is silverlight I used e.Key and key.Right and the program doesn't work good because the arrows do the 2 functions moving and write ./-. How I can work this out in Silverlight? (My English not good)
The code ( window form):
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (sender is TextBox)
{
TextBox textBox = (TextBox)sender;
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
{
e.Handled = true;
char insert;
if (e.KeyCode == Keys.Left)
{ insert = '.'; }
else
{ insert = '-'; }
int i = textBox.SelectionStart;
textBox.Text = textBox.Text.Insert(i, insert.ToString());
textBox.Select(i + 1, 0);
}
}
}
(and Silverlight):
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (sender is TextBox)
{
TextBox textBox = (TextBox)sender;
if (e.Key == Key.Left || e.Key == Key.Right)
{
e.Handled = true;
char insert;
if (e.Key == Key.Left)
{ insert = '.'; }
else
{ insert = '-'; }
int i = textBox.SelectionStart;
textBox.Text = textBox.Text.Insert(i, insert.ToString());
textBox.Select(i + 1, 0);
}
}
}
I don't understand, is there huge different effect between using Keycode/Key开发者_运维百科s and Key/Key or because something else?
The KeyDown event will not proportionate for several keys in TextBox, as TextBox uses those keys internally and marks those as e.Handled before they get to custom user code.
Here is the MSDN quote that explains the issue further:
Another example is TextBox. Some keys such as the ARROW keys are not considered text by TextBox and are instead considered specific to the control UI behavior, and the TextBox marks these event cases as handled.
If I were you, I'd just use the KeyUp event as your custom code does appear to work fine in that event.
Sincerely,
-- Justin Angel
You have to set
e.Handled = true;
so the event won't be consumed further down the route.
精彩评论