XAML Trigger Auto-tab when MaxLength is Reached

荒凉一梦 提交于 2019-12-10 17:29:11

问题


How can I incorporate an auto-tab when the MaxLength property is reached into a XAML Trigger, DataTrigger, PropertyTrigger, Style.Trigger, etc. Below are two such options for how I have already accomplished this with a TextBox via code-behind. I'm looking to apply it in a XAML style as well. Thanks.

XAML:

<TextBox x:Name="MyTextBox"
            Text="{Binding Path=MyProperty}"
            Style="{StaticResource TextBoxStyle}"
            MaxLength="5"
            TextChanged="MyTextBox_TextChanged">
</TextBox>

Code-Behind for WPF:

private void MyTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (MyTextBox.Text.Length == MyTextBox.MaxLength)
    {
        Keyboard.Focus(NextTextBox);
    }
}

private void MyTextBox_PreviewKeyDown(object sender, 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));
        }
    }
}

回答1:


simply do this in your Shell.xaml

 <Style TargetType="TextBox">
                <EventSetter Event="TextChanged" Handler="MyTextBox_PreviewKeyDown"/>
            </Style>

and in your shell.xaml.cs

private void MyTextBox_PreviewKeyDown(object sender, 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));
        }
    }
}


来源:https://stackoverflow.com/questions/4340419/xaml-trigger-auto-tab-when-maxlength-is-reached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!