New to Telerik UI for .NET MAUI? Start a free 30-day trial

Apply MaskedEntry Cursor Position at the Beginning

Environment

Version Product Author
6.1.0 Telerik UI for .NET MAUI MaskedEntry Dobrinka Yordanova

Description

This article shows how to set the CursorPosition property of the MaskedEntry control when the control receives Focus.

Solution

You need to define a MaskedEntry and when control receives focus, implement the logic to set the CursorPosition at the beginning of the text. Here is the code:

1. MaskedEntry definition in XAML:

<telerik:RadTextMaskedEntry Focused="RadTextMaskedEntry_Focused" Mask="#####" FontSize="26" x:Name="mask"/>

2. Focused event handler implementation:

private void RadTextMaskedEntry_Focused(object sender, FocusEventArgs e)
    {
        if (IsMaskEmpty(this.mask.Text))
        {
            RadEntry entry = ChildrenOfType<RadEntry>(this.mask).FirstOrDefault();
            if (entry != null)
            {
                this.mask.Dispatcher.DispatchDelayed(TimeSpan.FromSeconds(0.01), () =>
                {
#if IOS
                entry.CursorPosition = 1;                            
#endif
                    entry.CursorPosition = 0;
                });
            }
        }
    }

    private static IEnumerable<T> ChildrenOfType<T>(IView view)
    where T : IView
    {
        if (view is T t)
        {
            yield return t;
        }

        if (view is Layout layout)
        {
            foreach (var child in layout.Children)
            {
                foreach (var tChild in ChildrenOfType<T>(child))
                {
                    yield return tChild;
                }
            }
        }
    }

    private static bool IsMaskEmpty(string text)
    {
        foreach (var ch in text)
        {
            if (ch != '_')
            {
                return false;
            }
        }

        return true;
    }
In this article