Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textbox.TextChanged triggering when page is loaded. How do I prevent it?

I am having trouble with textbox.textchanged event. my textboxes are data-bound and when the page is loaded, textchanged event triggers. How do I prevent it from happening and only trigger when the user makes any sort of changes?

like image 374
will0809 Avatar asked Nov 02 '11 06:11

will0809


2 Answers

Inside textchanged event handlers you can verify if window (or usercontrol, or whatever) is loaded:

if (this.IsLoaded)
{
   //your logic here
}

This way you can skip the first firing of TextChanged events, when the window is not loaded yet.

like image 130
icebat Avatar answered Nov 15 '22 11:11

icebat


The problem is that whenever the text is set, TextChanged triggers. That is just the way WPF works. You can "fix" this by setting events in codebehind, by subscribing to the Loaded event of the Window/Usercontrol. The Loaded event fires after every child, and their childs, have finished loading, and is ready to be displayed.

<UserControl ---- Loaded="UserControl_Loaded">    
-
public void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    _txtBox.TextChanged += txt_changed;
}

public void txt_changed(object sender, RoutedEventArgs e)
{
   (...)
}
like image 43
AkselK Avatar answered Nov 15 '22 10:11

AkselK