Reputation: 10895
Initially this question brought me here: Disable firing TextChanged event
I wondered if jtmach's answer is "clean":
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;
}
Is it OK to unsubscribe TextChanged
-events in another event like this?
Or is it prone to errors because during the LostFocus the TextChanged event could be called (either by the user or by the program)?
Upvotes: 4
Views: 188
Reputation: 203820
If this were in a multi-threaded context then it would be a problem. It would be possible for the TextChanged
event to be currently running when you unsubscribed, thus preventing you from making the assumption that it's running while this code is also running.
That said, in this case both methods will always be running in the UI thread, so while this code won't really be "broken" (you couldn't be running the text changed event simultaneously because the UI thread can only be running one of the two events at one time anyway) but it also doesn't serve a purpose and can just be removed (because the event can't be fired while this event handler is running because it's blocking the UI thread).
Upvotes: 2