2013-02-13 47 views
0

好吧,我真的陷入了這裏傢伙:/。我有一個(自定義!)屏幕鍵盤,我想使用正則表達式。在屏幕鍵盤上使用正則表達式

I成功創建了一個正則表達式,只允許0-9comma作爲普通鍵盤。

當然,這不適用於我的屏幕鍵盤。

我有一個代碼段工程...

但我也有一個空格鍵,退格鍵和2個鍵四處移動。

當我使用正則表達式如下代碼,並單擊空格,空格鍵或插入符號按鈕我得到這個錯誤:

Object reference not set to an instance of an object. 

我在做什麼錯?

// the regex code 
    private Control keyb = null; 
    private void EditProdPriceEx_GotFocus(object sender, RoutedEventArgs e) 
    { 
     string AllowedChars = "[^0-9,]"; 
     if (Regex.IsMatch(EditProdPriceEx.Text, AllowedChars)) 
     { 
      keyb = (Control)sender; 
     } 
    } 

空格鍵:

private void KnopSpatie_Click(object sender, RoutedEventArgs e) 
    { 
     TextBox tb = keyb as TextBox; 
     int selStart = tb.SelectionStart; // here is where i get the error 
     string before = tb.Text.Substring(0, selStart); 
     string after = tb.Text.Substring(before.Length); 
     tb.Text = string.Concat(before, " ", after); 
     tb.SelectionStart = before.Length + 1; 
    } 

退格鍵:

private void KnopWissen_Click(object sender, RoutedEventArgs e) 
    { 
     TextBox tb = keyb as TextBox; 
     int cursorPosition = tb.SelectionStart; // here is where i get the error 
     if (cursorPosition > 0) 
     { 
      tb.Text = tb.Text.Substring(0, cursorPosition -1) + tb.Text.Substring(cursorPosition); 
      tb.SelectionStart = cursorPosition - 1; 
     } 
    } 

移動插入符左鍵:

private void KnopLinks_Click(object sender, RoutedEventArgs e) 
    { 
     TextBox tb = keyb as TextBox; 
     if (tb.SelectionStart > 0) // here is where i get the error 
     { 
      int selStart = tb.SelectionStart; 
      string before = tb.Text.Substring(0, selStart); 
      string after = tb.Text.Substring(before.Length); 
      tb.SelectionStart = before.Length - 1; 
     } 
    } 

移動插入符號右移按鈕:

private void KnopRechts_Click(object sender, RoutedEventArgs e) 
    { 
     TextBox tb = keyb as TextBox; 

     if (tb.SelectionStart >= 0) // here is where i get the error 
     { 
      int selStart = tb.SelectionStart; 
      string before = tb.Text.Substring(0, selStart); 
      string after = tb.Text.Substring(before.Length); 
      tb.SelectionStart = before.Length + 1; 
     } 
    } 
+1

哇......它與交易無關* ......確實很奇怪! – mortb 2013-02-13 11:24:00

+0

@mortb對不起,我編輯了錯誤,我在荷蘭發現了這些錯誤,所以我把它翻譯錯了! – DeMama 2013-02-13 11:28:01

+1

你有什麼錯誤?你不檢查'null'。 – 2013-02-13 11:28:53

回答

0

我想你一定要試試這個。在第一個代碼中。

// the regex code 
private Control keyb = null; 
private void EditProdPriceEx_GotFocus(object sender, RoutedEventArgs e) 
{ 
    string AllowedChars = "[^0-9,]"; 
    if (Regex.IsMatch(EditProdPriceEx.Text, AllowedChars)) 
    { 
     keyb = (Control)sender; 
    } 
} 

你讓KEYB空,而不是由你提到的任意鍵(空格等),我認爲這不產生錯誤設定的基準設定。你能檢查一下嗎?

+0

我的屏幕鍵盤需要'keyb = null;',它會將'A'或'B'等東西發送到文本框。所以我認爲我在錯誤的地方看。 – DeMama 2013-02-13 12:15:22

+0

是的,我知道,但對於正則表達式,如果按空格鍵例如,請保留'keyb = null',因爲您沒有設置它,並且引用仍然爲null。 – sebmaldo 2013-02-13 12:26:16

+0

ahaaa!是的,這確實很有意義!我會看看,謝謝:) – DeMama 2013-02-13 12:32:39