禁用触发TextChanged事件

Ms.*_*ody 6 c# wpf textbox lostfocus textchanged

我有文本框,当我lostFocus被解雇时我正在更改其中的文本,但这也会激活textChanged我正在处理的事件,但是我不想在这种情况下解雇它,我怎么能在这里禁用它?

更新:

这个想法bool很好,但我有几个文本框,我对所有这些都使用相同的事件,所以它并不像我想要的那样完全正常工作.

现在它正在运作!:

private bool setFire = true;

private void mytextbox_LostFocus(object sender, RoutedEventArgs e)
   {
      if (this.IsLoaded)
      { 
          System.Windows.Controls.TextBox textbox = sender as System.Windows.Controls.TextBox;

          if(textbox.Text.ToString().Contains('.'))
          {
             textbox.Foreground = new SolidColorBrush(Colors.Gray);
             textbox.Background = new SolidColorBrush(Colors.White);

             setFire = false;
             textbox.Text = "something else";
             setFire = true;
          }

      }
   }

private void mytextbox_TextChanged(object sender, TextChangedEventArgs e)
   {
      if ((this.IsLoaded) && setFire)
      {
         System.Windows.Controls.TextBox textbox = sender as System.Windows.Controls.TextBox;

         if(textbox.Text.ToString().Contains('.'))
         {
            textbox.Foreground = new SolidColorBrush(Colors.White);
            textbox.Background = new SolidColorBrush(Colors.Red);
         }  
       }

       setFire = true;
   }
Run Code Online (Sandbox Code Playgroud)

我设法在编辑文本后bool重新开始true,这样就可以了.所以这些人:]

小智 10

只需删除事件处理程序,然后在完成所需操作后添加它.

private void mytextbox_LostFocus(object sender, RoutedEventArgs e)
{
  this.mytextbox.TextChanged -= this.myTextBox_TextChanged;

  if(textbox.Text.ToString().Contains('.'))
  {
         textbox.Foreground = new SolidColorBrush(Colors.Gray);
         textbox.Background = new SolidColorBrush(Colors.White);
  }

  this.mytextbox.TextChanged += this.myTextBox_TextChanged;    
}
Run Code Online (Sandbox Code Playgroud)


Tig*_*ran 9

我能想到的最简单的方法是使用条件bool变量.当您要设置文本时LostFocus将其设置为truetextChanged事件处理程序内部检查该bool变量是否true,不执行任何操作.