2010-04-17 33 views
0

我有這個代碼窗口窗體應用程序,我一直試圖將其轉換爲Silverlight應用程序,但它不工作!有一個文本框,我附加了KeyDown事件處理程序。當用戶按下箭頭鍵(左側或右側)時,將焦點放在文本框上,它會寫入。要麼 -。當它是窗口形式我使用e.KeyCode和Keys.Right及其作品很好,但是當它是Silverlight時,我使用了e.Key和key.Right,程序不能正常工作,因爲箭頭執行2個函數移動和寫入./-。我如何在Silverlight中解決這個問題? (我的英語不太好)從Winform轉換簡單的代碼到Silverlight應用程序的問題

代碼(窗口形式):

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); 
       } 
      } 
     } 

(和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); 
       } 
      } 
     } 

我不明白,有沒有使用之間巨大的不同效果鍵碼/鍵和鍵/鍵還是因爲別的?

回答

0

你必須設置

e.Handled = true; 

因此事件不會進一步下跌的路徑消耗。

+0

我已經做了,但還是有問題 – Sara 2010-04-17 23:22:39

+0

該死的,我需要睡眠:/ – Femaref 2010-04-17 23:34:30

1

KeyDown事件對於TextBox中的幾個鍵不會成比例,因爲TextBox在內部使用這些鍵,並在它們到達自定義用戶代碼之前將它們標記爲e.Handled。

這裏是MSDN報價進一步解釋了這個問題:

另一個例子是文本框。某些鍵 (例如箭頭鍵)不是 被TextBox視爲文本,而是 而是被視爲特定於 控制UI行爲,TextBox 將這些事件情況標記爲已處理。

如果我是你,我只是使用KeyUp事件,因爲你的自定義代碼似乎在該事件中工作正常。

真誠,
- 賈斯汀天使

+0

是感謝你的信息。但也使用keyUp不能解決問題,導致光標在使用左/右箭頭時仍然移動。我想知道是否有禁用箭頭鍵的功能? – Sara 2010-04-20 20:52:24