2011-10-06 71 views
0

我有一個System.Windows.Controls.TextBox,我想表現如下:當你點擊它,它是動態確定,如果TextBox獲得焦點與否。這裏是包含在完成這一嘗試失敗了玩具應用:動態防止文本框變得焦點

<!-- MainWindow.xaml --> 
<Window x:Class="Focus.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition></RowDefinition> 
      <RowDefinition></RowDefinition> 
     </Grid.RowDefinitions> 
     <Label Name="myLabel" Grid.Row="0" Background="Red"></Label> 
     <TextBox Name="myTextbox" Grid.Row="1" Background="Green"></TextBox> 
    </Grid> 
</Window> 

// MainWindow.xaml.cs 
using System; 
using System.Windows; 
using System.Windows.Input; 

namespace Focus 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus; 
     } 

     private static readonly Random myRandom = new Random(); 

     private void myTextbox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) 
     { 
      int randomInt = myRandom.Next(0, 2); // 0 or 1 
      myLabel.Content = randomInt; 
      if(randomInt==0) 
      { 
       // PREVENT FOCUS - INSERT CODE HERE. (The line below is a failed attempt.) 
       FocusManager.SetFocusedElement(this, myLabel); 
      } 
     } 
    } 
} 

回答

2

下面的代碼,似乎這樣的伎倆:

// PREVENT FOCUS - INSERT CODE HERE. 
myLabel.Focusable = true; 
myLabel.Focus(); 
myLabel.Focusable = false; 

我也改變了這行代碼:

myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus; 

成這樣:

myTextbox.GotFocus += myTextbox_GotKeyboardFocus; 
1

我希望你知道你迷上了鍵盤焦點(TAB鍵)。

void textBox1_GotFocus(object sender, System.EventArgs e) 
{ 
    if (!this.checkBox1.Checked) 
     this.checkBox1.Focus(); 

    else 
     this.textBox1.Focus(); 

} 
+0

的GotKeyboardFocus事件當您單擊文本框時也會觸發。 – user181813

+0

我試圖將你的想法整合到我的示例代碼中(通過調用myLabel.Focus()),並且不幸的是它似乎無法工作。 – user181813