2013-07-22 38 views
0

我綁定textbox1數據LostFocus事件。我設置了鍵盤導航。 Tabindex=7textbox1textbox2 keyboardNavigation TabIndex=8。現在我的問題是我正在做textbox1的正則表達式驗證,如果我在textbox1中輸入無效字符,它顯示爲MessageBox說無效,只要點擊確定,它將導航到textbox2,我想將此鍵盤導航設置爲textbox1,直到我輸入有效字符。我怎樣才能做到這一點?如何設置keyboardnavigation.Tabindex代碼

我試着這樣說:

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> 

回答

0

嘗試去退了幾步......當我複製你的代碼到一個新的項目,並增加了幾個TextBoxes,它已經這樣做了,你是什麼後。 MessageBox彈出,我點擊OK和重點留在textBox1。這是我期望的行爲。

,我建議你,這是你的代碼的其他地方正在移動的邏輯重點textBox2,甚至您在WindowUserControl設置了TextBox ES存在於一個屬性。

+0

但對我來說它仍進入textbox2 ..我刪除keyboardNavigation.TabIned在xaml中的兩個文本框 – kida

+0

我也添加了xaml代碼..並且我正在使用LostFocus中的代碼tetxbox1的事件 – kida

+0

將事件LostFocus更改爲LostKeyBoardFocus事件時它的工作正常碼。 – kida