0

好的,我真的被困在这里了:/。我有一个(自定义!)屏幕键盘,我想使用正则表达式。

我成功地创建了一个正则表达式,只允许0-9一个comma常规键盘。

当然,这不适用于我的屏幕键盘。

我有一个有效的代码片段......

但我还有一个空格键、一个退格键和 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;
        }
    }
4

1 回答 1

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 设为 null,并且未由您提到的任何键(空格和其他)设置,我认为这会产生参考未设置错误。你能检查一下吗?

于 2013-02-13T11:45:40.010 回答