0

我有一个文本框,用户不应该被允许在其中写空格。

到目前为止,我有这个代码:

private void SearchCriteria_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key.ToString() == "Space")
    {
        DelLast = SearchCriteria.Text;
        NeedsToDelete = true;
    }
}

private void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (NeedsToDelete == true)
    {
        SearchCriteria.Text = DelLast;
        NeedsToDelete = false;
    }
}

它有效,但光标被放置在文本前面。还有另一种方法可以做到这一点吗?

4

2 回答 2

0

试试这个 :

    private void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (NeedsToDelete == true)
        {
            SearchCriteria.Text = DelLast;
            NeedsToDelete = false;
            SearchCriteria.Select(SearchCriteria.Text.Length, 0);
        }
    }
于 2013-07-19T13:37:56.817 回答
0

将SelectionStart保存在 OnKeyDown 事件中,然后在 OnKeyUpEvent 中再次设置

private void SearchCriteria_KeyDown(object sender, System.Windows.Input.KeyEventArgs e
{
    if (e.Key.ToString() == "Space")
    {
        DelLast = SearchCriteria.Text;
        NeedsToDelete = true;
        _selectionStart = SearchCriteria.SelectionStart;
    }
}
private void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (NeedsToDelete == true)
    {
        SearchCriteria.Text = DelLast;
        SearchCriteria.SelectionStart = _selectionStart;
        NeedsToDelete = false;
    }
}
于 2013-07-19T18:47:13.613 回答