【问题标题】:How to set keyboardnavigation.Tabindex from code如何从代码中设置keyboardnavigation.Tabindex
【发布时间】:2013-07-20 18:29:18
【问题描述】:

我在LostFocus 事件上绑定textbox1 数据。我设置了键盘导航。 Tabindex=7 用于textbox1textbox2 键盘导航TabIndex=8。现在我的问题是正在为textbox1 进行正则表达式验证,如果我在textbox1 中输入无效字符,它会显示MessageBox 说无效,并且一旦单击确定,它将导航到我想要设置的textbox2键盘导航到textbox1,直到我输入有效字符。我怎样才能做到这一点?

我试过这样:

if (!string.IsNullOrEmpty(txtbox1.Text))
{
    if(Regex.IsMatch(txtbox1.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
    {
        txtbox2.Text = "(" + txtbox1.Text + ")";
    }
    else
    {
        MessageBoxResult mbr;
        mbr=MessageBox.Show("please enter valid Email Id", "VMS", MessageBoxButton.OK, MessageBoxImage.Error);

        if (mbr == MessageBoxResult.OK)
        {
            Keyboard.Focus(txtbox1);
            txtbox1.Clear();
            // txtbox1.TabIndex = 7;
            //txtbox1.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));
            // txtbox2.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        }

        //txtbox1.Focus();                

        // KeyboardNavigation.SetTabIndex(txtbox1, 6);
     }
}
else
{
    txtbox2.Text = string.Empty;
    // txtbox1.TabIndex = 7;
    //txtbox1.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
    //KeyboardNavigation.SetTabIndex(txtbox1, 7);
    // txtbox2.TabIndex=7;
    //Keyboard.Focus(txtbox2);
}

如果输入的文本无效,如何将键盘导航设置为txtbox1?任何建议。

编辑:添加 xaml

  <Window x:Class="DataBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
<Grid>
    <TextBox Name="txtbox1" Margin="71,22,82,195" LostFocus="txtbox1_LostFocus" />
    <TextBox Name="txtbox2" Margin="71,96,82,127" />

</Grid>

【问题讨论】:

    标签: wpf c#-4.0 keyboard-navigation


    【解决方案1】:

    尝试返回几个步骤...当我将您的代码复制到一个新项目并添加了几个TextBoxes 时,它已经完成了您的任务。 MessageBox 弹出,我点击了OK,焦点停留在textBox1。这是我预期的行为。

    我向您建议,将逻辑焦点移至 textBox2 的是您在其他地方的代码,甚至可能是您在 TextBoxes 所在的 WindowUserControl 上设置的属性。

    【讨论】:

    • 但对我来说,它仍然转到 textbox2..我在 xaml 中删除了两个文本框的 keyboardNavigation.TabIned
    • 我也添加了 xaml 代码..并且正在使用 tetxbox1 的 LostFocus 事件中的代码
    • 当将 LostFocus 事件更改为 LostKeyBoardFocus 事件时,上述代码的工作正常。
    • 很高兴您发现了问题。 :)
    • 谢谢。由于我正在学习 WPF,请您推荐任何书籍来很好地了解 WPF 概念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多