title: Dynamically preventing a TextBox from getting focus
body: <p>I have a <code>System.Windows.Controls.TextBox</code> which I would like to behave as follows: When you click it, it is determined dynamically if the <code>TextBox</code> gets focus or not. Here's a toy application which contains a failed attempt at accomplishing this:</p>
  
  <pre><code>&lt;!-- MainWindow.xaml --&gt;
  &lt;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"&gt;
      &lt;Grid&gt;
          &lt;Grid.RowDefinitions&gt;
              &lt;RowDefinition&gt;&lt;/RowDefinition&gt;
              &lt;RowDefinition&gt;&lt;/RowDefinition&gt;
          &lt;/Grid.RowDefinitions&gt;
          &lt;Label Name="myLabel" Grid.Row="0" Background="Red"&gt;&lt;/Label&gt;
          &lt;TextBox Name="myTextbox" Grid.Row="1" Background="Green"&gt;&lt;/TextBox&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  
  // 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);
              }
          }
      }
  }
  </code></pre>