Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

TextChanged event looping round multiple times

$
0
0

I've created an Entry control using xaml as below

    <Entry x:Name="txtAge"
       Placeholder="Age"
       Keyboard="Numeric"
       TextColor="DarkBlue"
       PlaceholderColor="DarkBlue"
       Completed="AgeCompleted"
       HorizontalOptions="Start"
       WidthRequest="55"
       TextChanged="OnAgeTextChanged"
      />

When typing, the OnAgeTextChanged event it validation the text entered into the control.

private void OnAgeTextChanged(object sender, TextChangedEventArgs e)
{
// Creates a new instance of the age text box
var entry = (Entry)sender;

        try
        {
            // Removes the TextChanged property from the entry control
            entry.TextChanged -= OnAgeTextChanged;

            // if the newly-add character makes the length > 3
            if (entry.Text.Length > 3)
            {
                // Updates the entry to revert back to the 3 digit string
                entry.Text = e.OldTextValue;
            }

            string strName = entry.Text;

            if (strName.Contains(".") || strName.Contains("-"))
            {
                strName = strName.Replace(".", "").Replace("-", "");
                entry.Text = strName;
            }
        }

        catch(Exception ex)
        {
            Console.WriteLine("Exception caught: {0}", ex);
        }

        finally
        {
            // Re-assigns the TextChanged method to the entry control
            entry.TextChanged += OnAgeTextChanged;
        }
     }

However, it appears that the more times I type into the control, the more loops it appears to do.

As an example:
Typing "1" into the control - 1 loop, which is fine.
Typing "2", to make "12" - 2 loops
Typing "3", making "123" - 4 loops
Typing "4", to check it remains at "123" - 24 loops
Typing "5", to check it remains at "123" - Lots of loops, I believe there was over 90!

Why is this happening? I'm not sure, as I'm removing the event handler and re-assigning AFTER I've updated the value. Has anyone got any ideas?


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>