Search code examples
c#mauimaui-community-toolkit

.net MAUI Community Toolkit 'Changing' event for an ObservableProperty


I want to truncate the value of a data bound ObservableProperty in my program. It was my understanding that the OnXXXXXXChanging event (where XXXXXX is the variable name) is supposed to run before the actual value of the ObservableProperty is set.

For Example:

[ObservableProperty]
private string referenceNumber = string.Empty;

Then suppose regardless of what is entered, I want to trim the value of the ObservableProperty down to 10 characters at most. So I implement

partial void OnReferenceNumberChanging(string? oldValue, string newValue)
{
    if (newValue.Length > 10)
    {
        newValue = newValue.Substring(0, 10); 
    }
}

The challenge is that after this code runs and I interrogate the value of the ReferenceNumber ObservableProperty, it shows all the characters that were entered and not just the 10 the new value was trimmed down to. Am I missing something? Is this not an acceptable location to do this type of validation / modification?


Solution

  • I usually let the event complete with the error, allowing the invalid input, but, schedule a post fix-up, e.g.

    partial void OnReferenceNumberChanging(string? oldValue, string newValue)
    {
        if (newValue.Length > 10)
        {
            Application.Current.MainPage.Dispatcher.Dispatch(() =>
            {
                ReferenceNumber = ReferenceNumber.Substring(0, 10);
            });
        }
    }
    

    This sort of validation is necessary, because .NET MAUI doesn't appear to have any obvious way of blocking invalid input at the time it occurs.

    This pattern is needed for more complex fix-up such as regex pattern mask.