Search code examples
data-bindingmaui

Prevent Binding Loop with TextChanged-Event


I have an Entry with implemented TextChanged-Event in XAML of my .NET MAUI App.

I wanted to prevent an empty Entry-Text and set „0“ instead when it‘s empty.

So, in TextChanged-Event I assigned my .Text to „0“ in case of string.IsNullOrEmptyCharacter(e.NewCalue). But now, in my model the bound value property is hit in Debugger in an endless-loop.

How would I solve this? Still wanted to make sure that the Text is updated by both, changes in the model as well the model, when Text is chanted/deleted.

How should I do this?


Solution

  • Since you have not posted your code, I'll give a generic answer.

    The infinite loop occurs because your text-changed method is changing the value, thus firing text-changed again.

    The solution is to make sure you "do nothing" if text-changed fires due to your programmatic change.

    One way to do this, is to "do nothing", if your logic doesn't actually cause a change:

    ... MyTextChanged(string oldValue, string newValue)
    {
        string alteredNewValue = newValue;
    
        ... // Logic that examines newValue, MAYBE comes up with a different value.
    
        // Avoids infinite loop, in case above logic tries to set same value again
        if (alteredNewValue == newValue)
            return;   // DON'T set the property again!
    
        // CAUTION: POTENTIAL INFINITE LOOP.
        MyTextProperty = alteredNewValue;
    }
    

    ANOTHER POSSIBLE FIX

    Maybe there is a lurking issue if the property is set again during the TextChanged handler. If so, a simpler fix is to queue the property setting, so it happens after Maui has completed its changed processing:

    ...
    Dispatcher.Dispatch(() => MyTextProperty = alteredNewValue);