Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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)
{
   (...)
}

Well, from your comment I gather that you want the user to make changes which are only propagated to the underlying data when he explicitly saves or closes the form.

You could use the UpdateSourceTrigger "Explicit" here.

<TextBox Text={Binding MyData, UpdateSourceTrigger=Explicit}/>

So your changes are only propagated by explicitly calling UpdateSource on your bindings when your user hits the save button.

If you use MVVM you can also implement the same logic codewise into the ViewModels.

I had the same problem and ended up with a work around.

On the window I added a variable for window loaded and I set this at the end of the Window_Loaded event to true.

On the TextChanged events check if your variable is true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top