到达Textbox MaxLength时允许删除C#AutoTab

时间:2017-06-15 13:42:56

标签: c# wpf

我正在使用WPF 我想在' MaxLength'时自动切换到下一个texbox。到了。
我找到了这段代码:XAML Trigger Auto-tab when MaxLength is Reached
而且它正在发挥作用。但问题是,当达到MaxLength时我无法删除文本! 我也无法改变实际的文字 您是否有想法允许我修改或删除MaxLength到达文本框中的文本? 我的XAML:

<TextBox Grid.Column="0" Name="txtC1" Margin="5" MaxLength="7" PreviewKeyDown="txt1_PreviewKeyDown"></TextBox>
<TextBox Grid.Column="1" Name="txt2" Margin="5" MaxLength="12" PreviewKeyDown="txt2_PreviewKeyDown"></TextBox>
<TextBox Grid.Column="2" Name="txt3" Margin="5" MaxLength="12" PreviewKeyDown="txt3_PreviewKeyDown"></TextBox>

代码背后

private void txt1_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        // Auto-tab when maxlength is reached
        if (((TextBox)sender).MaxLength == ((TextBox)sender).Text.Length)
        {
            // move focus
            var ue = e.OriginalSource as FrameworkElement;
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

2 个答案:

答案 0 :(得分:0)

问题是你在keyDown上使用事件,这意味着当按下退格或删除时,事件被触发但文本在keyDown事件完成之前没有改变,因此代码将始终验证在textBox中使用相同数量的字符,并且在框中键入一个字符以触发更改焦点。

你可以这样做 XAML

<TextBox Grid.Column="0" Name="txtC1" Margin="5" MaxLength="7" TextChanged="txt1_TextChanged"></TextBox>
<TextBox Grid.Column="1" Name="txt2" Margin="5" MaxLength="12" TextChanged="txt2_TextChanged"></TextBox>
<TextBox Grid.Column="2" Name="txt3" Margin="5" MaxLength="12" TextChanged="txt3_TextChanged"></TextBox>

代码

    private void txt1_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (((TextBox)sender).MaxLength == ((TextBox)sender).Text.Length)
        {
            // move focus
            var ue = e.OriginalSource as FrameworkElement;
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

你仍然可以为其他东西做一些keyDown事件,例如:只允许某些键,如数字或特殊数字,但最好用textChanged事件验证文本长度。

答案 1 :(得分:0)

我解决了自己的问题。感谢我得到的不同答案,我稍微使用了它们 这是我的新代码:

private void txt1_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        // Auto-tab when maxlength is reached
        if (((TextBox)sender).MaxLength == ((TextBox)sender).Text.Length)
        {
            if(e.Key != Key.Delete && e.Key != Key.Clear && e.Key != Key.Back && ((TextBox)sender).SelectionLength == 0)
            {
                // move focus
                var ue = e.OriginalSource as FrameworkElement;
                e.Handled = true;
                ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            } 

        }
    }

它正在发挥作用。

相关问题